shell - MongoDB db collection linking -
shell - MongoDB db collection linking -
suppose have 2 collection in 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 want query in students collection through teachers name. this:
db.students.find({'teachers.name':"ta"}).count()
i have read somewhere possible link collection or embed it. there way it?
what have tried? have tried db.students.ensureindex({'teachers':1})
not work. think should not work. going out of clue how it?
duplicate: know there lot of post has similar title, yet confused!
have looked how relational models done mongodb?
i unsure why think ensureindex here. there no way "link" collections, mongodb non-relational database. there no way query can defined querying 2 collections separately using sub selects @ moment.
the main problem embedding here have many many relationship:
a pupil has many teachers a teacher has many studentswhich create unperformant scenario updating here.
the best, right now, off top of head bring together client side so:
var teachers = []; db.teachers.find({'name':"ta"}).foreach(function(doc){ teachers[teachers.legnth-1] = doc._id; }); db.students.find({teachers: {$in: teachers}});
shell mongodb
Comments
Post a Comment