MongoDB: map relationships in collection

1k Views Asked by At

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.

1

There are 1 best solutions below

3
On BEST ANSWER

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()