【发布时间】:2017-01-07 21:54:06
【问题描述】:
我有一个基于 mongo 的应用程序,它显示报告。 在每个报告中,用户可以发布显示给所有其他用户的 cmets,以及回复现有的 cmets。 cmets 有两个“级别”,顶级 cmets 没有“父母”,回复“父母”。评论存储在一个数组“discussions”中,每个评论都有另一个名为“replies”的数组。
db.reports.findOne()
{
"_id" : "L154654258",
"timestamp" : ISODate("2016-03-17T01:15:00Z"),
"title" : "Server Offline",
"content" : "A server has become offline due to reason X112",
"discussions" : [
{
"id" : ObjectId("57beb8068d9da75ed44e0ebc"),
"user_id" : "david",
"timestamp" : ISODate("2016-03-17T01:15:00Z"),
"comment" : "Is this the first time that it happens?",
"last_edit" : null,
"replies" : [
{
"id" : ObjectId("57beb8068d9da75ed44e0ebd"),
"user_id" : "gene",
"timestamp" : ISODate("2016-03-17T01:20:00Z"),
"comment" : "I have never seen anything like that before",
"last_edit" : null
},
{
"id" : ObjectId("57c480b7ee568ddc634fd977"),
"user_id" : "david",
"timestamp" : ISODate("2016-03-20T01:20:00Z"),
"comment" : "Thanks!",
"last_edit" : null
}
}
]
}
到目前为止,使用此方案,我能够使用位置 $ 运算符处理向每个评论(父母和回复)插入新项目,以及编辑父母的内容(如果用户选择编辑他们的帖子) . 我的问题是更新回复。我试过这个(我认为它不起作用,只是想测试一下):
db.reports.findOne({'_id': 'L154654258', 'discussions': {'$elemMatch': {'id': ObjectId("57beb8068d9da75ed44e0ebc"), 'replies': {'$elemMatch': {'id': ObjectId("57beb8068d9da75ed44e0ebd")}}}}},
{'$set' : {'discussions.$.replies.$.comment': "This is a test!", 'discussions.$.replies.$.last_edit': 'Fantastic'}}
)
用 findOne() 测试这个查询似乎表明查询的 find 部分有效。但是,如何更新数组的数组元素? 我假设两次使用 $ 运算符是行不通的,但是有没有办法做到这一点,或者我需要使用 Javascript 吗? 谢谢!
【问题讨论】:
-
是的,这就是数组嵌套过多的问题。你不能有效地与他们合作。在我们的应用程序中,我们只允许一级嵌入式数组,正是出于这个原因。
-
谢谢!我希望使用 javascript 来执行它(类似于下面的 Sharabanee 的回答)。将回复嵌套在“父”cmets 中是有意义的,因为我们希望限制每页显示的“父”cmets 的数量(无论这些 cmets 有多少回复)...
标签: mongodb