1

I have the following document structure...

{
  "id":"documentID"
  "sessionId":"sometext"
  "msg":"sometext"
  "time":"date"
}
  • sessionId can exist in many documents

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.

2
  • 1
    $addToSet isn't sorted, you need to use $push Commented Aug 14, 2013 at 21:56
  • Thank you .. and if I want to get with each msg the time also in the result? Commented Aug 14, 2013 at 22:07

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.