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

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


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