Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a unique ObjectId inside an update or aggregation?

Some sub documents in my collection are missing _ids. I've written this piece of mongo-shell code to try to add them.

db.jobs.updateMany({},
{
  $set: {
    "artifacts.$[elem]._id": new ObjectId()
  }
},
{
  arrayFilters: [
    {
      "elem._id": {
        $exists: false
      }
    }
  ]
})

This code succeeds in giving all the appropriate subdocuments _ids but it gives them all the same id. Any ideas on how to make the ids unique?

like image 417
Brian Drew Avatar asked Oct 20 '25 04:10

Brian Drew


1 Answers

Query

  • pipeline update with $function requires MongoDB >=4.4
  • i can't think of a way to generate it without javascript, but its simple with javascript like bellow
  • js will run on the server

*code can run on update with pipeline or an aggregate pipeline. *if we don't have a MongoDB aggregation operator we can always use javascript after 4.4

Test code here

db.collection.update({},
[
  {
    "$set": {
      "artifacts": {
        "$function": {
          "body": "function (ar) {return ar.map(x => { if(x.hasOwnProperty('_id')) return x; else {x[\"_id\"]=new ObjectId(); return x;}})}",
          "args": ["$artifacts"],
          "lang": "js"
        }
      }
    }
  }
],
{
  "multi": true
})
like image 145
Takis Avatar answered Oct 22 '25 19:10

Takis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!