Mongo多个组

时间:2014-01-30 11:47:24

标签: mongodb

我有下表:

{ _id:'',
  user_name: "test1"
  "date": "2014-01-30T10:14:50.004Z"
},
{ _id:'',
  user_name: "test2"
  date: "2014-01-17T15:48:20.420Z"
},
{ _id:'',
  user_name: "test3"
  date: "2014-01-24T18:07:14.627Z"
},

我需要获得每个用户每月的记录数,如下例所示:

{month:"01", "test1": 89, "test2":32, "test3":12},
{month:"02", "test1": 11, "test2":23, "test3":0}

数字 - 记录数

提前致谢!

2 个答案:

答案 0 :(得分:0)

Mongo Aggregation docs

中有一个非常类似的例子

答案 1 :(得分:0)

您需要以ISODate格式提供日期。

之后,您可以使用aggregate framework以您希望的格式获得结果。

您可以通过以下方式进入所需最终结果的中间阶段:

db.c.aggregate([ 
{$project: {_id:0, user_name: "$user_name", month: { $month: "$date" } } },
{$group: {_id:{month:"$month", user_name:"$user_name"}, count: {$sum:1} } },
{$project: {_id:0, month: "$_id.dmonth", user_name:"$_id.user_name", count: "$count"  } }
])

要在数组中获取结果,您可以附加 $ group ,如下所示:

db.c.aggregate([ 
{$project: {_id:0, user_name: "$user_name", month: { $month: "$date" } } }, 
{$group: {_id:{month:"$month", user_name:"$user_name"}, count: {$sum:1} } }, 
{$project: {_id:0, month: "$_id.month", user_name:"$_id.user_name", count: "$count"  } },
{$group: { _id: "$month", results: { $addToSet: { user_name: "$user_name", count: "$count" } } } },
{$project: {_id:0, month: "$_id", results: "$results"}}
])