0

While searching through the internet, I found out that joins can be emulated in mongodb through the map-reduce function. Going through the docs was confusing.

I have two collections: one with a list of friends of one user. And the other collection is of all the users. I want to fetch the profile pictures of all the friends. how do I create a mongodb query to get the desired results?

The USERS collection:

{
    "_id" : ObjectId("524c194a6e3715ce0a000001"),
    "email" : "qwerty@abc.com",
    "password" : "",
    "phone" : "",
    "salt" : "",
    "upic" : "someuser2fd2751259bb7519d7b760ffee9b7fce203ad1f34.jpg",
    "username" : "someuser2"
}
{
    "_id" : ObjectId("524be475fafb35480a000001"),
    "email" : "",
    "password" : "",
    "phone" : "",
    "salt" : "",
    "upic" : "amitverma2522b7a52e054c350f78fd7f3558919f2e2dab58.jpg",
    "username" : "amitverma"
}

The friends of each user collection:

{
    "_id" : ObjectId("526547ed2389630000000001"),
    "friends" : [
        {
            "_id" : ObjectId("524be475fafb35480a000001"),
            "username" : "amitverma"
        },
            {
            "_id" : ObjectId("524be475fafb35480a000001"),
            "username" : "someuser2"
        }

    ],
    "upic" : "macbookfd2751259bb7519d7b760ffee9b7fce203ad1f34.jpg",
    "username" : "someuser"
}

Help would be appreciated.

amit
  • 10,133
  • 22
  • 72
  • 121
  • multiple collections in the same query is impossible http://stackoverflow.com/questions/6502541/mongodb-query-multiple-collections-at-once – zamnuts Nov 23 '13 at 07:08

1 Answers1

0

There are no official docs for this as it's not a recommended best practice. It's complex that you need to do multiple passes carefully outputting the same results into the same collection.

You'd be better served by gathering the list of friends and using the $in operator (reference) to fetch the users and projecting the results to only include the fields you require (like the image).

Ideally, you'd cache those results locally to avoid needlessly requesting image paths. Following is untested code that should work in the shell:

db.friends.find({ username: 'someuser'}).forEach(friend_list) {
    // this would gather the list of friend's _ids
    // the _id will be passed as an array for the $in operator
    var friends = friend_list.friends.map(function(friend) { return this._id; });
    // gather up the images for each of the friends
    var upics = db.users.find({_id : { $in : friends }},
             { _id: 1, upic: 1 }).toArray();
    // now, do something with upics -- outside of the MongoDB shell, this will
    // return asynchronously ....
});
WiredPrairie
  • 58,954
  • 17
  • 116
  • 143