MongoDbB,按多个字段分组

时间:2017-01-08 08:03:18

标签: mongodb

对于Mongo而言,这是一个非常新的东西,我发现一些简单的东西,我会在SQL中用令人沮丧的难度来完成Mongo。

我有一个类似于下面的对象

[{
    "_id" : ObjectId("5870fb29a1fe030e1a2909db"),
    "updatedAt" : ISODate("2017-01-07T14:28:57.224Z"),
    "createdAt" : ISODate("2017-01-07T14:28:57.224Z"),
    "state" : "Available",
},
{
    "_id" : ObjectId("5870fb29a1fe030e1a2909dc"),
    "updatedAt" : ISODate("2017-01-07T14:28:57.224Z"),
   "createdAt" : ISODate("2017-01-07T14:28:57.224Z"),
   "state" : "notReady",
},
{
   "_id" : ObjectId("5870fb29a1fe030e1a2909d9"),
    "updatedAt" : ISODate("2017-01-07T14:28:57.224Z"),
   "createdAt" : ISODate("2017-01-07T14:28:57.224Z"),
   "state" : "Disconnected",
}]

我想要做的是按最大日期和状态对数据进行分组。 理想情况下,我要寻找的结果将类似于以下内容。

{
latestDate: "2017-01-07T14:28:57",
states : {
  available : 10,
  disconnected : 5,
  notReady : 2
}}

基本上我正在寻找与此等效的SQL:

SELECT createdAt, state, COUNT(rowid)
FROM db
WHERE date = (SELECT MAX(createdAt) FROM db)
GROUP BY 1,2

我在这里搜索并发现了一些不错的信息,但我可能会错过一些直接的信息。到目前为止,我只能成功到达这里

db.collection.aggregate([
{$project: {"_id" : 0,"state": 1, "date" : "$createdAt"}},
{$group :  {"_id" : {"date":"$date", "state": "actual"}, "count":{"$sum":1}}}
]) 

任何帮助将不胜感激:)

1 个答案:

答案 0 :(得分:0)

db.collection.aggregate([
{
    $group : {
        _id : {
            date : "$createdAt",
            state : "$state"
        },
        count : {$sum : 1}
    }
},
{
    $group : {
        _id : "$_id.date",
        states : {
            $addToSet : {
                state : "$_id.state",
                count : "$count"
            }
        }
    }
},
{
    $sort : {_id : -1}
},
{
    $limit : 1
},
{
    $project : {
        _id : 0,
        latestDate : "$_id",
        states : "$states"
    }
}
])

输出:

{
    "latestDate" : ISODate("2017-01-07T14:28:57.224Z"),
    "states" : [
             {
                     "state" : "Available",
                     "count" : 1
             },
             {
                     "state" : "notReady",
                     "count" : 1
             },
             {
                     "state" : "Disconnected",
                     "count" : 1
             }
     ]
}