Emmanuel P
Emmanuel P

Reputation: 185

MongoDB Group by / Map reduce

Hey guys I have an existing messaging schema in mongoDB which works well.

{       
    "_id" : ObjectId("4f596b4543658618c0000004"),
    "user_id" : ObjectId("4f4c6c5143658618dc000002"),
    "body" : "message body",
    "from_user" : {
        "_id" : ObjectId("4f4c6b6943658618dc000001"),
        "name" : "Mister Quin"
    },
    "created_at" : ISODate("2012-03-09T02:30:29Z")
}

Now I want to display a list of people a given user has messaged. You can think of it as a message inbox that combines messages I am the sender and recipient of denoted by "user_id", and "from_user._id" respectively. So in essence group unique messages between two parties from the message collection. Any help I can get would be appreciated. I know it's probably a map reduce problem.

I am using mongoid as my ORM but that shouldn't matter much here.

Thanks.

Upvotes: 0

Views: 452

Answers (1)

Kyle Banker
Kyle Banker

Reputation: 4359

You can use group and group by from_user._id and user_id.

db.messages.group({key: {'from_user._id': 1, user_id: 1},
                   initial: {sum: 0}, 
                   reduce: function(doc, prev) {prev.sum += 1},
                   cond: {from_user._id: ObjectId("4f4c6b6943658618dc000001")})

That will return a list of all users messaged by Mister Quin, and the number of times each was messaged. Make sure you have an index on "from_user._id"

Upvotes: 1

Related Questions