4

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?

Takis
  • 8,314
  • 2
  • 14
  • 25
Brian Drew
  • 43
  • 4

1 Answers1

2

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
})
Takis
  • 8,314
  • 2
  • 14
  • 25