大家好,我是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"}
}
}
}
)伙计们,我在拼命地寻求帮助。我想学习这方面的知识。
发布于 2013-05-08 08:01:03
有几件事正在发生。
首先,您想使用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"}
}
}
)我要重申我不喜欢这种模式--你没有限制你的文档增长,这会导致性能问题,更不用说让它变得比你需要的更复杂(也更大)。
https://stackoverflow.com/questions/16430095
复制相似问题