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.???" } } ])
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.
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.
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.
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.
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" } } } ])
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With