Reputation: 7540
Suppose I have two collection in a mongoDB
students:
{_id: 1, name: "sa", teachers:[1,2,3]}
{_id: 2, name: "sb", teachers:[1,3]}
teachers:
{_id:1, name: "ta"}
{_id:2, name: "tb"}
{_id:3, name: "tc"}
now I want to query in students collection through teachers name. Like this:
db.students.find({'teachers.name':"ta"}).count()
I have read somewhere that it is possible to link collection or embed it. Is there any way to do it?
what have I tried? I have tried db.students.ensureIndex({'teachers':1})
but it does not work. I also think it should not work. I am going out of clue how to do it?
DUPLICATE: Well I know that there are a lot of post which has similar title, but yet I am confused!
Upvotes: 0
Views: 267
Reputation: 43884
Have you looked into how relational models are done with MongoDB?
I am unsure why you think ensureindex will do anything for you here. There is no way to "link" collections, MongoDB is a non-relational database. There is also no way that a query can be defined as querying two collections separately using sub selects at the moment.
The main problem with embedding here is that you have a many to many relationship:
Which could create a unperformant scenario with updating here.
The best, right now, off the top of my head is to actually do the JOIN client side like so:
var teachers = [];
db.teachers.find({'name':"ta"}).forEach(function(doc){
teachers[teachers.legnth-1] = doc._id;
});
db.students.find({teachers: {$in: teachers}});
Upvotes: 1