mongodbmongoosemongodb-queryaggregation-framework

Mongo how to convert id to string without losing all fields


I am trying to convert id to string in aggregate function with

  {
    "$project": {
      "_id": {
        "$toString": "$_id"
      }
    }
  }

But for some reason i am losing all other fields after aggregation and get only "_id" field. What should i change?

Mongo Playground


Solution

  • When you use $project on _id explicitly and with an expression or 1 then it's like selecting only the _id field.

    Usually, _id is included by default so the usage is like { $project: { _id: 0 } } - the 0 means "don't include _id in the result" but include all other fields.

    Read more about the behaviour of $project here.

    Instead, just use $set:

      {
        "$set": {
          "_id": {
            "$toString": "$_id"
          }
        }
      }
    

    Your Mongo Playground example, with the fix.