Search code examples
mongodbmongodb-queryprojection

MongoDB findOneAndUpdate projection


I'm currently using MongoDB and using the findOneAndUpdate method. I'm trying to use the projection however it doesn't seem to be working 100% successfully.

Here is the projection:

{
  orderID: '$_id',
  _id: false,
  user: true,
  guild: true,
  order: true,
  status: true,
  orderExpiry: true,
  priority: true,
  sentAt: true
}

As you can see, I'm trying to set orderID to the value of _id however, it doesn't do anything.

Here is the code I am executing for reference :

await this.db.collection('orders').findOneAndUpdate(filter, { $set: { ...data } },
                  { returnOriginal: false, projection: this.getProjectionFields() });

I hope someone can help me, thank you!


Solution

  • As far as I know projection with .find() or similar .findOneAndUpdate() does not support field transformations(adding new field out of existing) which $project in aggregation is capable of doing. So projection can be used just to include or exclude certain fields from result. Although this is true but up-to certain extent this is false, we can transform an array field using projection operators, Check : projection.