3

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?

Marco
  • 322
  • 1
  • 3
  • 15
  • 1
    I don't think it is possible to generate new id for each document, because it runs a single transaction. you have to loop the result in your client side language and generate the object id. – turivishal Jan 24 '22 at 10:16
  • If `anId` only needs to be a unique ID, I recommend using a type different than `ObjectId`, perhaps a UUIDv4. – Buzz Moschetti Jan 24 '22 at 19:28
  • I have the exact same problem, but I'm running mongo 4.2 without $function support. How did you solve this? – John Doherty Nov 17 '22 at 12:54

1 Answers1

3

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

{
  anId: {
    $function: {
      body: function() {
        return new ObjectId();
      },
      args: [],
      lang: 'js'
    }
  }
}
1sina1
  • 937
  • 7
  • 11
  • not working :( it returns nothing – Marco Jan 24 '22 at 14:24
  • 1
    it retruns the object for me on mongodbCompass, try to change retrun new ObjectId() to return new ObjectId().valueOf(); – 1sina1 Jan 24 '22 at 15:26
  • Creating a new ObjectId is a client-side oriented thing. Although there does not seem to be specific guidance against it, there is something about generating the ID server-side that is unsettling. Again, it is *not* the DB engine that generates an ObjectId for `_id` if unset -- it is rather the client-side driver that detects absence of field `_id` upon insert and creates it on the fly. – Buzz Moschetti Jan 24 '22 at 19:33