添加一个文档,这是MongoDB中一个字段的累积

问题描述 投票:0回答:2

如何在集合中添加一个在MongoDB中累积值集合字段的文档?

我有一个MongoDB集合,其中包含以下格式的文档:

{
  "_id" : 3876435465554,
  "title" : "xxx",
  "category" : "xxx",
  ...
}

所以愿望的结果是:

{ "_id" : "All", "num" : 28 }  // <- This is the document that I want include in the output
{ "_id" : "xxx", "num" : 11 }
{ "_id" : "yyy", "num" : 8 }
{ "_id" : "zzz", "num" : 9 }

到目前为止,我试过这个:

db.collection.aggregate([
  { $project: { title:1, category:1} },
  { $group: {
      _id: { _id:"$category"},
      num: { $sum: 1 }
    } },
  { $project: { _id:"$_id._id", num:1} },
  { $sort: { _id:1} }
])

但是,只生成没有“全部”文档的文档:

{ "_id" : "xxx", "num" : 11 }
{ "_id" : "yyy", "num" : 8 }
{ "_id" : "zzz", "num" : 9 }

我不知道如何使用所有“枚举”值的总和添加“全部”文档。

注意:链接2调用aggregates我能够在程序中得到欲望输出,但想法是只用一个aggregate得到输出。

mongodb mongodb-query aggregation-framework
2个回答
1
投票

您可以在3.4中使用以下聚合查询。

更改包括添加额外的$group来计算总计数,同时将各个计数行推入数组,然后使用$concatArrays将总行文档添加到单个计数数组。

$unwind回到扁平结构,并由_id和$replaceRoot排序,以推动所有文档达到顶级水平。

db.collection.aggregate([
  {"$project":{"title":1,"category":1}},
  {"$group":{"_id":{"_id":"$category"},"num":{"$sum":1}}},
  {"$group":{
    "_id":null,
    "total":{"$sum":"$num"},
    "rest":{"$push":{"num":"$num","_id":"$_id._id"}}
  }},
  {"$project":{"data":{"$concatArrays":[[{"_id":"all","num":"$total"}],"$rest"]}}},
  {"$unwind":"$data"},
  {"$sort":{"data._id":1}},
  {"$replaceRoot":{"newRoot":"$data"}}
])

1
投票

您可以使用$facets“链接”数据库端的管道,因此它将是来自客户端的单个请求:

db.collection.aggregate([
  { $match: { category: { $ne: 'all' } } },
  { $project: { title:1, category:1 } },
  { $facet: {
      total: [ 
        { $group: {
          _id: 'all', 
          num: { $sum: 1 }
         } },
      ],
      categories: [   
        { $group: {
          _id: "$category",
          num: { $sum: 1 }
         } },
      ]
  } },
  { $project: { all: { $concatArrays: [ "$total", "$categories" ] } } },
  { $unwind: "$all" },
  { $replaceRoot: { newRoot: "$all" } },  
  { $sort: { _id:1 } }
])
© www.soinside.com 2019 - 2024. All rights reserved.