Search code examples
mongodbmongodb-querypipelineaggregationprojection

MongoDB generates same ObjectId with new ObjectId in pipeline's $project stage


As last stage of my pipeline, I have a $project like this :

{
  ...
  anId : new ObjectId()
}

But mongo is generating the same Id for each document. I want it to generate a new different Id for each projected document. How to do so within the pipeline?


Solution

  • you can do it with the help of $function aggregation:

    {
      anId: {
        $function: {
          body: function() {
            return new ObjectId();
          },
          args: [],
          lang: 'js'
        }
      }
    }