更新与条件匹配的mongoose数组
我的模式看起来像
{ qty:{ property1:{ //something } property2:[{ size:40, color:"black", enabled:"true" }] } }
属性2是数组我想要做的是更新那些在单个查询中启用为true的数组对象
我试着写下面的查询
db.col.update({ "qty.property2.enabled" = "true" }, { "qty.property2.color" = "green" }, callback)
但它不工作
错误:
[main]错误:不能有。 在字段名称[qty.pro.size]
db.col.update({"qty.property2.enabled":"true"},{$set: {'qty.property2.$.color': 'green'}}, {multi: true})
这是更新数组内的元素的方式。
- 等号'='不能在对象内部使用
- 更新数组使用$完成
假设你的文档看起来像这样。
{ "_id" : ObjectId("4f9808648859c65d"), "array" : [ {"text" : "foo", "value" : 11}, {"text" : "foo", "value" : 22}, {"text" : "foobar", "value" : 33} ] }
那么你的查询将是
db.foo.update({"array.value" : 22}, {"$set" : {"array.$.text" : "blah"}})
第一个大括号表示查询条件,第二个设置新值。