您好我有一个系列:
{
"_id" : ObjectId("508d27069cc1ae293b36928d"),
"title" : "This is the title",
"body" : "This is the body text.",
"created_date" : ISODate("2012-10-28T12:41:39.110Z"),
"comments" : [
{
"subject" : "This is coment 1",
"body" : "This is the body of comment 1.",
"author_id" : ObjectId("508d345f9cc1ae293b369296"),
"created_date" : ISODate("2012-10-28T13:34:23.929Z")
},
{
"subject" : "This is coment 2",
"body" : "This is the body of comment 2.",
"author_id" : ObjectId("508d34739cc1ae293b369297"),
"created_date" : ISODate("2012-10-28T13:34:43.192Z")
},
{
"subject" : "This is coment 3",
"body" : "This is the body of comment 3.",
"author_id" : ObjectId("508d34839cc1ae293b369298"),
"created_date" : ISODate("2012-10-28T13:34:59.336Z")
}
]
}
所以,在仪表板的一个页面上,我想看到所有评论,我该怎么做?如何在单个集合中获取每个帖子的所有评论,我如何识别每个评论(用于编辑或删除)?
UPD1:
这是来自posts集合的文档。我想得到这样的东西:
[
...,
{
"_generated_id_for_identify": [What the data?],
"subject" : "This is coment 1",
"body" : "This is the body of comment 1.",
"author_id" : ObjectId("508d345f9cc1ae293b369296"),
"created_date" : ISODate("2012-10-28T13:34:23.929Z")
},
{
"_generated_id_for_identify": [What the data?],
"subject" : "This is coment 2",
"body" : "This is the body of comment 2.",
"author_id" : ObjectId("508d34739cc1ae293b369297"),
"created_date" : ISODate("2012-10-28T13:34:43.192Z")
},
...,
{
"_generated_id_for_identify": [What the data?],
"subject" : "This is coment N",
"body" : "This is the body of comment N.",
"author_id" : ObjectId("508d34839cc1ae293b369298"),
"created_date" : ISODate("2012-10-28T13:34:59.336Z")
},
...
]
答案 0 :(得分:3)
在帖子集合中聚合并通过“_id”匹配,然后在评论和提示中使用展开,您可以在结果键中获得新的评论集合。
db.posts.aggregate([
{$match:{_id:ObjectId("508d27069cc1ae293b36928d")}},
{$unwind:"$comments"},
{$project:{
"_id":{id:"$_id",dt:"$comments.created_date"},
subject:"$comments.subject",
body:"$comments.body",
"autor_id":"$comments.author_id",
"created_date":"$comments.created_date"}} ]).result
但是通过匹配posts._id的简单查询,您可以获得post.comments