'update aggregate doesn't modify all the documents
Sample data:
{
_id: ,
instances: [
{
instance_id: ObjectId()
}
]
}
I need to convert to ObjectId to String format in the instances array.
I came up with the below query
db.test.update(
{'_id': {'$in': ['1054605|2347', '1053095|2404']}},
[
{
$set: {
i: {
$map: {
input: "$instances",
as: "instance",
in: {
$mergeObjects: [
"$$instance",
{
instance_id: {
$cond: {
if: {
$eq:[ { $type: "$$instance.instance_id"} , "objectId"]
},
then: {
$convert:{
input: "$$instance.instance_id",
to: "string"
}
},
else: "$$instance.instance_id"
}
}
}
]
}
}
}
}
}
])
But the above query works for only one document. But it doesn't work on multiple documents, it simply says updated 0 documents.
Any suggestions please?
Solution 1:[1]
You are using the update method:
By default, the db.collection.update() method updates a single document. Include the option multi: true to update all documents that match the query criteria.
All you have to do is add the multi: true
flag to the update options, like so:
db.collection.update(
<query>,
<update>,
{
multi: true,
}
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Tom Slabbaert |