问题描述
我是 mongodb 的新手.
I am new to mongodb.
我有一个这样的数据库:
I have a database like this:
{
"universe": "DC",
"characters": [
{"name": "superman", "selected": true},
{"name": "wonder woman", "selected": false},
{"name": "flash", "selected": false}
},
{
"universe": "marvel",
"characters": [
{"name": "wolverine", "selected": false},
{"name": "cyclops", "selected": false}
}
如果universe
是DC",我正在尝试更新它的characters
,其中角色的name
等于wonder"女人",然后我希望所属的 selected
字段更新为 true
并且在同一个文档中,与 name
不匹配的字符《神奇女侠》在选择
I'm trying to make if the universe
is "DC", update its characters
where the character's name
equals "wonder woman", then I want the belonging selected
field to be updated to true
and in this same document, characters that do not match the name
of "wonder woman" have the value of false
in selected
mydb.collection.findOneAndUpdate(
{
"universe": "DC", //only DC universe
"characters.name":"wonder woman"
},
{
$set: {
"characters.$.selected": true, // I dont know how to set false to other objects where name!=wonder woman
},
})
想要的结果:
{"name": "superman", "selected": false},
{"name": "wonder woman", "selected": true},
{"name": "flash", "selected": false}
我该怎么做?
推荐答案
从 MongoDB 3.6 开始,更新数组字段时,可以指定 arrayFilters 确定要更新哪些数组元素.
Starting in MongoDB 3.6, when updating an array field, you can specify arrayFilters that determine which array elements to update.
mydb.collection.findOneAndUpdate(
{
universe: "DC"
},
{
$set : {
"characters.$[has].selected" : true,
"characters.$[not].selected" : false
}
},
{
arrayFilters: [
{
"has.name": { $eq: "wonder woman" }
},
{
"not.name": { $ne: "wonder woman" }
}
],
returnNewDocument: true
}
)
- 以下操作查找
universe
字段等于DC"的文档 - 使用过滤位置运算符
$[]
和arrayFilters
将selected
修改为true
用于characters
数组中的所有元素,其中name
(has.name) 是$eq
到 ";神奇女侠" - 另一边的
arrayFilters
将characters
数组中所有元素的selected
修改为false
name
(not.name) 是$ne
到神奇女侠". returnNewDocument: true
返回更新的文档- The following operation finds a document where the
universe
field equals "DC" - uses the filtered positional operator
$[<identifier>]
with thearrayFilters
to modify theselected
totrue
for all elements in thecharacters
array where thename
(has.name) is$eq
to "wonder women" - other side the
arrayFilters
to modify theselected
tofalse
for all elements in thecharacters
array where thename
(not.name) is$ne
to "wonder women". returnNewDocument: true
return updated document
这篇关于如何根据条件更新具有 2 个可能值的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!