$project to contain the latest date from the group

时间:2015-05-24 20:25:11

标签: mongodb aggregation-framework

I have a collection that is filled with messages, and I want to get a group of how many messages there are per room.

  • Gets messages within the last hour
  • Where gameId = 5550d868c5242fb3299a2604
  • Grouped by $room
  • Sorted by created

When I add the projection, the count works, but _id becomes null, and created doesn't even return.

What I am looking for is _id to contain $room, created to contain the newest date, and count to be the count of items.

db.chatMessages.aggregate([
    {
        $match: {
            created: {
                $gte: new Date((new Date()) - (1000 * 60 * 60))
            },
            gameId: ObjectId("5550d868c5242fb3299a2604")
        }
    },
    {
        $project: {created: 1}
    },
    {
        $group: {
            _id: "$room",
            count: {$sum: 1}
        }
    },
    {
        $sort: {created: -1}
    }
])

Here is some example data:

{
    "gameId" : ObjectId("5550d868c5242fb3299a2604"),
    "message" : "For real?",
    "room" : "Main",
    "name" : "Hello",
    "created" : ISODate("2015-05-24T17:49:43.868Z"),
    "_id" : ObjectId("55620f376aa13616759f4f06")
}
{
    "gameId" : ObjectId("5550d868c5242fb3299a2604"),
    "message" : "Yeah for reals...",
    "room" : "Main",
    "name" : "Jim",
    "created" : ISODate("2015-05-24T17:49:59.135Z"),
    "_id" : ObjectId("55620f476aa13616759f4f07")
}

Here is the returned output:

{
    "result" : [ 
        { 
            "_id" : null, 
            "count" : 4 
        } 
    ], 
    "ok" : 1 
}

Here is what I am looking for:

{
    "result" : [ 
        { 
            "_id" : "Main", 
            "count" : 4,
            "created" : ISODate("2015-05-24T17:37:19.331Z")
        } 
    ], 
    "ok" : 1 
}

So what is causing this to break when I add the $project?

1 个答案:

答案 0 :(得分:1)

I was able to get it by adding created to the group and doing $max on the column like this:

db.chatMessages.aggregate([
    {
        $project: {room: 1, created: 1}
    },
    {
        $match: {
            created: {
                $gte: new Date((new Date()) - (1000 * 60 * 60 * 20000))
            },
            gameId: ObjectId("5550d868c5242fb3299a2604")
        }
    },
    {
        $group: {
            _id: "$room",
            count: {$sum: 1},
            created: {$max: "$created"}
        }
    },
    {
        $sort: {created: -1}
    }
])