$ group获取数组中所有相关数据

时间:2018-12-11 16:50:35

标签: mongodb mongodb-query aggregation-framework

我想查询文档并返回代表所有类别的对象列表,每个类别对象中都有一个对象数组,其中包含与该类别匹配的文档。

如果有助于解释:数据库中有代表新闻文章的文档列表,我需要在前端按类别对它们进行显示,因此我需要为每个类别提供一个对象,每个类别对象都包含在该类别下显示的一系列文章(作为对象)。

我有以下格式的文件:

{ 
    "date" : ISODate("2018-06-25T00:00:00.000+0000"), 
    "detail" : {
        "category" : "world", 
        "title" : "stuff is happening", 
        "content" : "lorem ipsum dolor"
    } 
}
{ 
    "date" : ISODate("2018-03-08T00:00:00.000+0000"), 
    "detail" : {
        "category" : "national", 
        "title" : "more stuff is happening", 
        "content" : "sit amet"
    } 
}
{ 
    "date" : ISODate("2018-02-02T00:00:00.000+0000"), 
    "detail" : {
        "category" : "local", 
        "title" : "local stuff is happening", 
        "content" : "not much happening locally"
    }
}

...我希望我的结果看起来像这样:

{  _id: "world",
   count: 3,
   "articles" : {[
       {
       "date" : ISODate("2018-06-25T00:00:00.000+0000"), 
       "detail" : {
           "category" : "world", 
           "title" : "stuff is happening", 
           "content" : "lorem ipsum dolor"
       },
       {
       "date" : ISODate("2018-06-25T00:00:00.000+0000"), 
       "detail" : {
           "category" : "world", 
           "title" : "stuff is happening #2", 
           "content" : "lorem ipsum dolor"
       },
       {
       "date" : ISODate("2018-06-25T00:00:00.000+0000"), 
       "detail" : {
           "category" : "world", 
           "title" : "stuff is happening #3", 
           "content" : "lorem ipsum dolor"
       }
    ]}
}
{ _id: "national",
   count: 1,
   "articles" : {[
     {
       "date" : ISODate("2018-03-08T00:00:00.000+0000"), 
       "detail" : {
           "category" : "national", 
           "title" : "more stuff is happening", 
           "content" : "sit amet"
       } 
     }
}

...等等。到目前为止,我有这个查询:

db.news_feed.aggregate([
{ $match: {} },
{ $group: {_id:'$detail.category', count: { $sum:1 } } },
{ $addFields: {
                    "article": "$$ROOT"
                }
} 
])

这为我提供了每个类别的汇总计数,但是显然$$ ROOT将结果插入$ group之后,而不是原始文档之后:

{ 
    "_id" : "world", 
    "count" : 3.0, 
    "articles" : {
        "_id" : "world", 
        "count" : 3.0
    }
}
{ 
    "_id" : "national", 
    "count" : 1.0, 
    "brief" : {
        "_id" : "national", 
        "count" : 1.0
    }
}
{ 
    "_id" : "local", 
    "count" : 5.0, 
    "brief" : {
        "_id" : "local", 
        "count" : 5.0
    }
}
.
.

如何插入要汇总的原始文章的“文章”数组?

1 个答案:

答案 0 :(得分:1)

您需要在$push阶段使用$group累加器

db.news_feed.aggregate([
  { "$group": {
    "_id": "$detail.category",
    "articles": { "$push": "$$ROOT" },
    "count": { "$sum": 1 }
  }}
])