assaf_miz84
assaf_miz84

Reputation: 687

Mongodb Aggregation framework group and sort

I have the following document structure...

{
  "id":"documentID"
  "sessionId":"sometext"
  "msg":"sometext"
  "time":"date"
}

I want to aggregate the documents by sessionId, the result for each session should contain the set of messages related to the session sorted by time.

Using the MongoDB aggregation framework how can I achieve that?

I have tried to sort first and then group but the messages in each session wasn't sorted for some reason:

{ $sort: { "time": 1 } },
{ "$group" : { 
    "_id" : "$sessionId", 
    "msgs" : { "$addToSet" : "$msg" }
} }

any suggestions? your answer is highly appreciated.

Upvotes: 1

Views: 6331

Answers (1)

Mason
Mason

Reputation: 8846

You can do this:

db.collection.aggregate( 
    {$sort:{"time":1}},
    { $group:
        { _id: "$sessionId",
        messages: { "$push": {message: "$msg", time: "$time"} }
        }
    } 
)

This will sort the collection based on time then group by session id. Each session ID group will have an array of sub-documents which contain the message and time of the message. By sorting then pushing the messages will be ordered by time in your messages array.

Upvotes: 6

Related Questions