MongoDB,如何分组文件

时间:2016-11-18 05:24:52

标签: mongodb mongodb-query aggregation-framework

我的收藏集包含以下数据:

[
  {
    "code": 1,
    "location": "1 QUEEN STREET",
    "_id": "1",
  },
  {
    "code": 1,
    "location": "2 KING STREET",
    "_id": "2"
  },
  {
    "code": 2,
    "location": "1 QUEEN STREET",
    "_id": "3"
  },
  {
    "code": 2,
    "location": "2 KING STREET",
    "_id": "4"
  },
  {
    "code": 2,
    "location": "2 KING STREET",
    "_id": "5"
  }

]

寻找可以按照" location"并为每个文档添加一组代码,其中包含每个唯一代码的计数。

输出将是这样的:

[
  { "location": "1 QUEEN STREET", "codes":["code1":1,"code2":1]},
  { "location": "2 KING STREET", "codes":["code1":1,"code2":2]}
]

我尝试过这样的查询:

aggregate([{ $group : { _id : "$location", codes: { $addToSet: "$code",count: { $sum: 1 } } } }])

aggregate([{ $group : { _id : "$location", codes: {$group:{_id:"$_code",count:{$sum :1}}} } }])

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

aggregate(
[
    { $group : { 
            _id : { location: "$location", code: "$code"},
            count: { $sum:1 }
        } 
    },
    { $group: {
            _id: "$_id.location", 
            codes: {$addToSet: {"code":"$_id.code", "count":"$count"}}
        } 
    },
    { $project: { location: "$_id", codes: 1, _id: 0}},
]
)

结果:

{ "codes" : [ { "code" : 1, "count" : 1 }, { "code" : 2, "count" : 1 } ], "location" : "1 QUEEN STREET" }
{ "codes" : [ { "code" : 1, "count" : 1 }, { "code" : 2, "count" : 2 } ], "location" : "2 KING STREET" }

注意:无法获得所需的输出,如果列表中的元素存在格式错误,则应使用dict {}

答案 1 :(得分:0)

您可以在聚合操作中使用两个$group步骤。首先,您要计算每个代码和每个位置的文档数。接下来,您只需查看位置,并将$push计数以及相应的代码放入数组

[
{$group: {_id: {code: '$code', location: '$location'}, count: {$sum: 1}}},
{$group: {_id: '$_id.location', codes: {$push: {code: '$_id.code', count: '$count'}}}}
]