2016-11-23 81 views
1

嗨,我需要蒙戈DB更新查询帮助:蒙戈更新查询

此数据:

{ 
"services" : [ 
     { 
      "type" : "Financial Transaction", 
     }], 
"outStandingAmount" : 0 
} 

此查询工作正常。

db.getCollection( 'user_informations')updateMany。({ “outStandingAmount”:},{$设置:{ “outStandingAmount”:5000}})

但是,当我尝试更新此我有错误。

db.getCollection('user_informations').updateMany({"services.type":"Financial Transaction"},{$set: {"services.type":"Financial Trans"}}) 
+0

你能提供错误信息吗? – cjungel

回答

0

>当您找到文档时,您需要使用$操作符。

db.collection.updateMany(
    {"services.$.type":"Financial Transaction"}, 
    {$set: {"services.type":"Financial Trans"}} 
) 

更新您的代码,并在 的过滤部分取代services.typeservices.$.type

忽略我以前的查询

这将做到这

db.collection.find().forEach(function(doc) { 
    db.collection.update({"services.type":"Financial Transaction"}, 
         {$set:{"services.$.type":"Financial Trans"}}); 
}) 
2
db.collection.find().pretty() 

{"_id" : ObjectId("5836b428d7e99005c2585b08"), "services" : [{"type" : "Financial Transaction"}],"outStandingAmount" : 0} 
{"_id" : ObjectId("5836c5a9d7e99005c2585b09"), "services" : [{"type" : "Financial Transaction"}], "outStandingAmount" : 2000} 

下面的查询将做匹配的记录更新。

db.collection.updateMany({"services.type":"Financial Transaction"}, {$set:{ 
"services":[{"type":"Financial Trans"}]}}); 

因为我们有我们的收集 两个匹配记录上述updateMany查询的结果是

{ "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 } 

而如果我们用

db.getCollection('user_informations').updateMany({"services.type":"Financial Transaction"},{$set: {"services.type":"Financial Trans"}}) 

,我们会得到一个错误味精

"errmsg" : "cannot use the part (services of services.type) to traverse the element ({services: [ { type: \"Financial Transaction\" } ]})" 

当涉及数组时,则'。'用于遍历数组元素,即使我们可以使用'。'遍历嵌套数组,但是对于修改数组我们有一组运算符,请参阅https://docs.mongodb.com/v3.2/reference/operator/update-array/

也'。'在使用位置运算符$时用于更新查询。