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

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

Leave a Comment