matus
matus

Reputation: 1582

how to $project ObjectId to string value in mongodb aggregate?

Is there an operator I could use in aggregate function to get a string instead of ObjectId in response?

db.something.aggregate([
  { "$match": { "property": { "$exists": true } } },
  { "$project": { "stringId": "$_id.???" } }
])

Upvotes: 57

Views: 69373

Answers (3)

Ashh
Ashh

Reputation: 46461

Mongodb 4.0 has introduced $toString aggregation operator. So, Now you can easily convert ObjectId to string

db.collection.aggregate([
  {
    $project: {
      _id: {
        $toString: "$_id"
      }
    }
  }
])

OR vice versa using $toObjectId aggregation

db.collection.aggregate([
  {
    $project: {
      _id: {
        $toObjectId: "$_id"
      }
    }
  }
])

Upvotes: 114

Tamil Arasi
Tamil Arasi

Reputation: 179

There is no Direct Operator in aggregate function to get String from ObjectId.

After version 2.6 You can use ObjectId.toString() method to convert your ObjectId to string. First you match and project your ObjectID. Then you can convert this object ID to string by using ObjectID.toString().

db.something.aggregate([{"$match":{'property': {$exists:true}}},{"$project":{"_id":1}}]) 

And then use resulting Object and get the string as response using ObjectID.tostring()

Edit: You can access the str attribute of the object id using

ObjectId("507f191e810c19729de860ea").str

source: mongodb docs

Upvotes: 11

user1260158
user1260158

Reputation: 1

You can do it inline using the $concat operator:

db.something.aggregate(
    [
        { $match :
            { 'property' :
                { $exists:true }
            }
        },
        { $project:
            { stringId:
                { $concat: [ ObjectId().str ] }
            }
        }
    ]
)

Upvotes: -17

Related Questions