4

I don't know how descriptive the title is, so feel free to modify it for better understanding.

I'm very new to MongoDB and so far things have gone well. However I ran into a very basic problem where I need to join / map documents from other collection to documents in other collection.

In brief I have following structure:

Collection "member":

{
  "_id": "abc",
  "name": "Mr. Abc"
}


{
  "_id": "def",
  "name": "Mrs. Def"
}

Collection "recent":

[{
  "_id": "123",
  "member_id": "abc",
  "action": "joined"
},
  "_id": "456",
  "member_id": "def",
  "action": "left"
}]

Now I want to iterate through "recent" and map all the members into it as a object "member" into document.

I'm using monk (https://github.com/LearnBoost/monk) as an API for MongoDB, but couldn't find any solution.

So far I tried to iterate with .forEach() and to add every result from "member" to "recent". However since the queries are asynchronous, I can't make it work with my callback which returns all the documents.

I read something about cursors and so on, but couldn't find any feasible solution. Therefore I'm asking from you.

Samuli Hakoniemi
  • 18,740
  • 1
  • 61
  • 74

1 Answers1

3

Mongo is non relational so no joins

2 queries:

var recent = db.recent.findOne({"id" : "123"})
db.member.find( {"id" : {$in : recent.member_id }});

Then it is upto you to use ORM like http://blog.modulus.io/getting-started-with-mongoose

ForEach based approach talks about loading client Side as mentioned by you already:

    db.recent.find().forEach(
        function (rece) {
            rece.member = db.member.find( {"id" : {$in : rece.member_id }});
            db.recentMembers.insert(rece);
        }
    );

db.recentMembers.find().pretty()
Abs
  • 3,902
  • 1
  • 31
  • 30
  • But I want to go through whole db.recent, not just findOne(). So do I have to loop and handle each document individually? I have also considered using Mongoose, thanks for pointing it out. – Samuli Hakoniemi Jun 01 '14 at 20:17
  • even i am exploring this i found this post useful http://stackoverflow.com/questions/2350495/how-do-i-perform-the-sql-join-equivalent-in-mongodb – Abs Jun 01 '14 at 20:27
  • 1
    I'll accept your answer since the idea behind it lead to me to working solution. Now I'm iterating the collection with findOne(), adding correct document into it and then after reaching the limit, I execute the callback function. – Samuli Hakoniemi Jun 01 '14 at 21:27