mongodb-如何在嵌套数组中查找和更新元素
这是集合:
db.employees.insertMany([
{
"data": {
"category": [
{
"name": "HELLO",
"subcategory": [
"EDUCATION",
"ART",
]
},
{
"name": "HELLO",
"subcategory": [
"GG",
"ART",
]
},
{
"name": "HELLO",
"subcategory": [
"EDUCATION",
"SHORE",
]
}
]
}
},
{
"data": {
"category": [
{
"name": "HELLO",
"subcategory": [
"EDUCATION",
"HELLO",
]
}
]
}
},
{
"data": {
"category": [
{
"name": "HELLO",
"subcategory": [
"GG",
"ART",
]
}
]
}
}
]);
我想要的是使用包含“教育”的“子类别”中的“类别”中的元素,然后用另一个字符串替换“教育”,例如“体育”。
我尝试了几个命令,但没有真正完成这项工作:
db.employees.updateMany({
"data.category.subcategory": "EDUCATION"
},
{
"$set": {
"data.category.$": {
"subcategory": "SPORTS"
}
}
})
我看到的是它不会通过更换元素来更新该元素,并且不能替换每个符合条件的元素。
Here is the collection:
db.employees.insertMany([
{
"data": {
"category": [
{
"name": "HELLO",
"subcategory": [
"EDUCATION",
"ART",
]
},
{
"name": "HELLO",
"subcategory": [
"GG",
"ART",
]
},
{
"name": "HELLO",
"subcategory": [
"EDUCATION",
"SHORE",
]
}
]
}
},
{
"data": {
"category": [
{
"name": "HELLO",
"subcategory": [
"EDUCATION",
"HELLO",
]
}
]
}
},
{
"data": {
"category": [
{
"name": "HELLO",
"subcategory": [
"GG",
"ART",
]
}
]
}
}
]);
What I want is to locate the elements in 'category' with a 'subcategory' that contains 'EDUCATION' and replace 'EDUCATION' with another string, let's say 'SPORTS'.
I tried a couple of commands but nothing really did the job:
db.employees.updateMany({
"data.category.subcategory": "EDUCATION"
},
{
"$set": {
"data.category.quot;: {
"subcategory": "SPORTS"
}
}
})
What I saw is that it doesn't update the element by replacing it and it doesn't replace every element that meets the criteria.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
想想 mongongodb更新带有聚合管道满足您的场景。
$ set
- setdata.category
value。1.1。
$ map
- 迭代data.Category
中的每个元素并返回数组。1.1.1。
$ MergeObjects
- 将当前文档与sub类别
字段合并, 1.1.1.1.1 。。1.1.1.1
$ map
- 从subcategory
数组中迭代每个值。使用$ cond
用教育
用sports
替换,请使用现有值($$ this this
) 。示例mongo playground
Think that MongoDB Update with Aggregation Pipeline fulfills your scenario.
$set
- Setdata.category
value.1.1.
$map
- Iterate each element indata.category
and return an array.1.1.1.
$mergeObjects
- Merge the current document with the document withsubcategory
field from 1.1.1.1.1.1.1.1
$map
- Iterate each value from thesubcategory
array. With$cond
to replace the wordEDUCATION
withSPORTS
if fulfilled, else use existing value ($$this
).Sample Mongo Playground
这是使用
“ ArrayFilters”
进行操作的另一种方法。尝试一下 mongoplayground.net.net 。
Here's another way to do it using
"arrayFilters"
.Try it on mongoplayground.net.