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?
Query
$function
requires MongoDB >=4.4*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
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With