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?
CodePudding user response:
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,
}
)
CodePudding user response:
So the issue here is the Model.update() function
Update() function updates one object but that behaviour can be overridden by adding the multi: true to the update function as mentioned in the documentation here.
Having said that, you can also use a more "cleaner" approach to the situation by using the updateMany() instead of update() with multi: true.
updateMany() is same as update(), except MongoDB will update all documents that match filter regardless of the value of the multi option.
This would offer a cleaner and more readable piece of code. Documentation to updateMany() can be found here.
