我在MongoDB中创建了几个文档:
> db.myCollection.insert( {"BUCKET": [{"Field1":"X"},{"Field2":{"A":"B","C":"D","E":"F"}}]} )
> db.myCollection.insert( {"BUCKET": [{"Field1":"Y"},{"Field2":{"G":"H","I":"J","K":"L"}}]} )
> db.myCollection.find()
{ "_id" : ObjectId("534102c492970f1b06b1edc8"), "BUCKET" : [ { "Field1" : "X" }, { "Field2" : { "A" : "B", "C" : "D", "E" : "F" } } ] }
{ "_id" : ObjectId("5341054e92970f1b06b1edc9"), "BUCKET" : [ { "Field1" : "T" }, { "Field2" : { "G" : "H", "I" : "J", "K" : "L" } } ] }
现在我想更新它,以便“BUCKET”的所有值都设置为[]
所以我试试这个:
db.myCollection.update({},{"BUCKET":[]}, false, false)
这部分奏效了。但它只将第一个桶改为[]:
> db.myCollection.find()
{ "_id" : ObjectId("534102c492970f1b06b1edc8"), "BUCKET" : [ ] }
{ "_id" : ObjectId("5341054e92970f1b06b1edc9"), "BUCKET" : [ { "Field1" : "T" }, { "Field2" : { "G" : "H", "I" : "J", "K" : "L" } } ] }
所以我尝试将“multi”字段更改为true并再次尝试。但它不起作用:
> db.myCollection.update({},{"BUCKET":[]}, false, true)
multi update only works with $ operators
如何使用update()方法更新多个子文档?
答案 0 :(得分:2)
您需要的是$set
运算符,您的更新查询才能正常运行。试试这个:
db.myCollection.update({},{$set:{"BUCKET":[]}}, false, true)