0

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!

1 Answer 1

1

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:

  • A student has many teachers
  • A teacher has many students

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}});
Sign up to request clarification or add additional context in comments.

1 Comment

+1. teachers = db.teachers.distinct("_id", {'name':"ta"}); db.students.find({teachers: {$in: teachers}}); reads a bit better perhaps and is more bandwidth friendly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.