通过 mongo shell 更新 mongoDB 中的嵌套数组 [英] Updating nested arrays in mongoDB via mongo shell
问题描述
以下是MongoDB文档:
Following is a MongoDB document:
{
"_id" : 2,
"mem_id" : M002,
"email" : "xyz@gmail.com",
"event_type" : [
{
"name" : "MT",
"count" : 1,
"language" : [
{
"name" : "English",
"count" : 1,
"genre" : [
{
"name" : "Action",
"count" : 6
},
{
"name" : "Sci-Fi",
"count" : 3
}
],
"cast" : [
{
"name" : "Sam Wortington",
"count" : 2
},
{
"name" : "Bruce Willis",
"count" : 4
},
{
"name" : "Will Smith",
"count" : 7
},
{
"name" : "Irfan Khan",
"count" : 1
}
]
}
]
}
]
}
由于嵌套,我无法更新数组类型的字段,特别是 event_type、语言、流派和演员表.基本上,我想更新所有四个提到的字段以及每个子文档的计数字段.如果值是新的,则更新语句应向树插入一个值,否则应增加该值的计数.
mongo shell 中的查询是什么?谢谢
I'm not able to update fields that is of type array, specially event_type, language, genre and cast because of nesting. Basically, I wanted to update all the four mentioned fields along with count field for each and subdocuments. The update statement should insert a value to the tree if the value is new else should increment the count for that value.
What can be the query in mongo shell?
Thanks
推荐答案
您直接遇到了 MongoDB 当前的限制之一.问题是引擎不支持多个位置运算符.请参阅此 多次使用位置 `$` 运算符来更新嵌套数组
You are directly hitting one of the current limitations of MongoDB. The problem is that the engine does not support several positional operators. See this Multiple use of the positional `$` operator to update nested arrays
对此有一个公开票:https://jira.mongodb.org/browse/SERVER-831(也在那里提到)
There is an open ticket for this: https://jira.mongodb.org/browse/SERVER-831 (mentioned also there)
您还可以阅读有关如何更改数据模型的文章:更新 mongodb 中的嵌套数组
You can also read this one on how to change your data model: Updating nested arrays in mongodb
如果对你来说可行,你可以这样做:
If it is feasible for you, you can do:
db.collection.update({_id:2,"event_type.name":'MT' ,"event_type.language.name":'English'},{$set:{"event_type.0.language.$.count":<number>}})
db.collection.update({_id:2,"event_type.name":'MT' ,"event_type.language.name":'English'},{$set:{"event_type.$.language.0.count":<number>}})
但你不能这样做:
db.collection.update({_id:2,"event_type.name":'MT' ,"event_type.language.name":'English'},{$set:{"event_type.$.language.$.count":<number>}})
这篇关于通过 mongo shell 更新 mongoDB 中的嵌套数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!