Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.???" } } ]) 
like image 729
matus Avatar asked Mar 17 '16 12:03

matus


People also ask

How to convert ObjectID to string in MongoDB aggregation?

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.

What is $project in MongoDB?

The $project takes a document that can specify the inclusion of fields, the suppression of the _id field, the addition of new fields, and the resetting of the values of existing fields. Alternatively, you may specify the exclusion of fields. The $project specifications have the following forms: Form. Description.

What are the differences between using aggregate () and find () in MongoDB?

With aggregate + $match, you get a big monolithic BSON containing all matching documents. With find, you get a cursor to all matching documents. Then you can get each document one by one.

Can we use $match in Find MongoDB?

Basically, MongoDB provides the different match operators such as $match and $count, etc, to the user and we can utilize them as per our requirement. We can also use a match operator for the aggregation pipeline. In the above syntax, we use the $match Mongodb operator as shown.


2 Answers

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"       }     }   } ]) 
like image 87
Ashh Avatar answered Sep 28 '22 09:09

Ashh


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

like image 21
Tamil Arasi Avatar answered Sep 28 '22 10:09

Tamil Arasi