0

你好,我有一个收藏:

{
    "_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:

这是来自帖子集合的文档。我想得到这样的东西:

[
    ...,
    {
         "_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")
    },
    ...
]
4

1 回答 1

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

于 2014-03-06T14:52:16.983 回答