Home > Back-end >  MongoDB generates same ObjectId with new ObjectId in pipeline's $project stage
MongoDB generates same ObjectId with new ObjectId in pipeline's $project stage

Time:01-25

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?

CodePudding user response:

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

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