你好我对mongodb相当新,而且诚实,因为我已经习惯了mysql,所以它仍然让我感到困惑,而且对json也不太了解。
以下是我在论坛
中的文件{
"_id" : ObjectId("5188c93f0361ca6dc33e3a30"),
"admin" : [ ],
"created" : "2013-04-30 19:10:21",
"description" : "guitar theory",
"members" : [ ],
"modified" : "2013-04-30 19:10:21",
"name" : "Arpeggios",
"posts" : [
{
"post_id" : "1",
"user_id" : "1",
"name" : "Test",
"slug" : "xxx",
"comment" : "xxx",
"created" : "xxx",
"modified" : "xxx",
"comments" : [ ],
"attachments" : [ ]
},
{
"post_id" : "2",
"user_id" : "1",
"name" : "Test",
"slug" : "xxx",
"comment" : "xxx",
"created" : "xxx",
"modified" : "xxx",
"comments" : [ ],
"attachments" : [ ]
}
],
"profile_pic" : "adasdad",
"settings" : [ ],
"slug" : "arpeggio"
}
我的目标是在数组注释上推送一个post_id = 1的元素,以获得图片这是我想要的结果:
{
"_id" : ObjectId("5188c93f0361ca6dc33e3a30"),
"admin" : [ ],
"created" : "2013-04-30 19:10:21",
"description" : "guitar theory",
"members" : [ ],
"modified" : "2013-04-30 19:10:21",
"name" : "Arpeggios",
"posts" : [
{
"post_id" : "1",
"user_id" : "1",
"name" : "Test",
"slug" : "xxx",
"comment" : "xxx",
"created" : "xxx",
"modified" : "xxx",
"comments" : [
{"comment_id":"xxx", "user_id":"xxx", "name":"xxx","comment":"xxx", "created":"xxx", "modified":"xxx"},
{"comment_id":"xxx", "user_id":"xxx", "name":"xxx","comment":"xxx", "created":"xxx", "modified":"xxx"}
],
"attachments" : [ ]
},
{
"post_id" : "2",
"user_id" : "1",
"name" : "Test",
"slug" : "xxx",
"comment" : "xxx",
"created" : "xxx",
"modified" : "xxx",
"comments" : [ ],
"attachments" : [ ]
}
],
"profile_pic" : "adasdad",
"settings" : [ ],
"slug" : "arpeggio"
}
我已经彻底研究了好几个小时了,这就是我提出来的,这只是失败而且不起作用:
db.discussions.update(
{_id:ObjectId("5188c93f0361ca6dc33e3a30"), posts:{post_id:1}},
{$push:
{"posts:
{comments:
{"comment_id":"xxx", "user_id":"xxx", "name":"xxx","comment":"xxx", "created":"xxx", "modified":"xxx"}
}
}
}
)
请伙计们,我拼命寻求帮助。我想了解这一点。
答案 0 :(得分:1)
有几件事正在发生。
首先,您要使用the $ positional operator。
其次,您提到您的收藏名称是讨论,但您的更新使用“讨论” - 请确保使用与实际收藏名称相同的名称。
第三,你列出的文件中的post_id是“1”,但你试图匹配1.字符串“1”不等于数字1.小心你的类型。
这种语法(注意我也纠正了不平衡的引号)应该这样做:
db.discussion.update(
{_id:ObjectId("5188c93f0361ca6dc33e3a30"), "posts.post_id":"1"},
{$push:
{"posts.$.comments":
{"comment_id":"xxx", "user_id":"xxx",
"name":"xxx","comment":"xxx", "created":"xxx",
"modified":"xxx"}
}
}
)
我将重申我不喜欢这种模式 - 你不会限制你的文档增长,这会导致性能问题,更不用说使它比你需要的更复杂(也更大)。