我有许多具有以下结构的文档(通过唯一的工具名称
),在db test
中:
{
"_id" : ObjectId("111111111111"),
"toolname" : "hammer",
"abilities" : [
{
"foo" : "blue",
"bar" : "beagle",
"LOE" : 0.65
},
{
"foo" : "red",
"bar" : "beagle",
"LOE" : 0.57
},
{
"foo" : "red",
"bar" : "fish",
"LOE" : 0.42
}
]
}
我可以使用以下查询找到
此文档:
db.test.find({"abilities.bar":"beagle","abilities.foo":"red"})
我想要做的是更新 LOE
,其中我在上面的 find
查询中设置的两个参数匹配。例如 - 如果 "powereds.bar":"beagle"
和 "powereds.foo":"red"
,则更新 "LOE"
将该对象中的 .99
。
Mongo 是否有一个内置函数,您可以仅在该对象中的另一个键等于某个值时设置键的值?或者我是否需要创建一个客户端函数来返回数组索引并基于该索引进行更新?示例:
some function(){...}
db.test.update({"abilities.bar":"beagle","abilities.foo":"red"}
{ $set: { "abilities[x].LOE" : .99 } }
)
最佳答案
使用$elemMatch如下:
db.collection.update({"abilities":{"$elemMatch":{"bar":"beagle","foo":"red"}}},
{"$set":{"abilities.$.LOE":0.99}})
关于javascript - 更新键值,其中不同的键等于某个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31273590/