Reputation: 92
Hi i need a help for mongo db update query:
For this Data:
{
"services" : [
{
"type" : "Financial Transaction",
}],
"outStandingAmount" : 0
}
This Query is working fine.
db.getCollection('user_informations').updateMany({"outStandingAmount":},{$set: {"outStandingAmount":5000}})
But when i try to update this I got error.
db.getCollection('user_informations').updateMany({"services.type":"Financial Transaction"},{$set: {"services.type":"Financial Trans"}})
Upvotes: 1
Views: 176
Reputation: 5466
db.collection.find().pretty()
{"_id" : ObjectId("5836b428d7e99005c2585b08"), "services" : [{"type" : "Financial Transaction"}],"outStandingAmount" : 0}
{"_id" : ObjectId("5836c5a9d7e99005c2585b09"), "services" : [{"type" : "Financial Transaction"}], "outStandingAmount" : 2000}
The below query will do the update on matching records.
db.collection.updateMany({"services.type":"Financial Transaction"}, {$set:{
"services":[{"type":"Financial Trans"}]}});
Since we had two matching records in our collection the result of the above updateMany query is
{ "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 }
Whereas if we use
db.getCollection('user_informations').updateMany({"services.type":"Financial Transaction"},{$set: {"services.type":"Financial Trans"}})
we will get an error msg
"errmsg" : "cannot use the part (services of services.type) to traverse the element ({services: [ { type: \"Financial Transaction\" } ]})"
When an array is involved then '.' is used to traverse into array elements, even we can traverse into nested arrays using '.', but for modifying an array we have a set of operators, please see https://docs.mongodb.com/v3.2/reference/operator/update-array/
also '.' is used on a update query when we use positional operator $.
Upvotes: 2
Reputation: 2650
> You need to make use of the $ operator when you find documents.
db.collection.updateMany( {"services.$.type":"Financial Transaction"}, {$set: {"services.type":"Financial Trans"}} )
update your code and replace
services.type
toservices.$.type
in the filter section.
ignore my previous query
this will do it
db.collection.find().forEach( function(doc) {
db.collection.update({"services.type":"Financial Transaction"},
{$set:{"services.$.type":"Financial Trans"}});
})
Upvotes: 0