如何将值按特定条件推送到多个嵌套数组中?
我有一份这样的文件
[
{
"_id": "class_a",
"students": [
{
"_id": "1a",
"name": "John",
"grades": []
},
{
"_id": "1b",
"name": "Katie",
"grades": []
},
{
"_id": "1c",
"name": "Andy",
"grades": []
},
]
}
]
要插入到嵌套数组中的查询。(不确定此处缺少什么)
db.collection.update({
"_id": "class_a",
"students": {
$elemMatch: {
"_id": {
"$in": [
"1a",
"1b"
]
}
}
}
},
{
$push: {
"students.$.grades": "A+"
}
})
得到以下结果。但我希望John
和Katie
在grades
中都有A+
[
{
"_id": "class_a",
"students": [
{
"_id": "1a",
"grades": ["A+"],
"name": "John"
},
{
"_id": "1b",
"grades": [],
"name": "Katie"
},
{
"_id": "1c",
"grades": [],
"name": "Andy"
}
]
}
]
预期结果
[
{
"_id": "class_a",
"students": [
{
"_id": "1a",
"grades": ["A+"],
"name": "John"
},
{
"_id": "1b",
"grades": ["A+"],
"name": "Katie"
},
{
"_id": "1c",
"grades": [],
"name": "Andy"
}
]
}
]
2条答案
按热度按时间nhhxz33t1#
您可以使用
$[<identifier>]
来只更新符合条件的项目。您的第一个{}
是寻找相关的文件,而arrayFilters
则是寻找文件巢状数组中的相关项目:了解它在playground example上的工作原理
d8tt03nd2#
你真的应该用arrayFilters,否则它只会匹配第一个实体。你根本不需要用$elemMatch。
Playground-https://mongoplayground.net/p/_7y89KB83Ho