Home > Net >  When attempting to add _ids to subdocuments the new _ids are all the same. How can I make them uniqu
When attempting to add _ids to subdocuments the new _ids are all the same. How can I make them uniqu

Time:11-20

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?

CodePudding user response:

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

*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
})
  • Related