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

matus picture matus · Mar 17, 2016 · Viewed 29.5k times · Source

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.???" } }
])

Answer

Ashh picture Ashh · Jul 8, 2018

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"
      }
    }
  }
])