Reputation: 63
I have more than two collections. Each collection has fields which are similar to the foreign key in MySQL. How can I display the whole collection's data. my example colletions.
collection one:
var mongoose = require('mongoose');
module.exports = mongoose.model('Addmodule',{
chapterid: {type: mongoose.Schema.ObjectId, ref: 'Addchapter' },
modul: String
});
collection two:
var mongoose = require('mongoose');
module.exports = mongoose.model('Addchapter',{
subjectid: {type: mongoose.Schema.ObjectId, ref: 'Addsubject' },
chapter: String
});
collection three:
var mongoose = require('mongoose');
module.exports = mongoose.model('Addsubject',{
classid: {type: mongoose.Schema.ObjectId, ref: 'Addclass' },
subject: String
});
Upvotes: 0
Views: 808
Reputation: 1428
With new version of mongodb(3.2), you can merge the collections. Please take a look $lookup aggregation method. Also you can check the examples in this page. If you have further questions, please feel free to ask, because your question is too general.
{
$lookup:
{
from: <collection to join>,
localField: <field from the input documents>,
foreignField: <field from the documents of the "from" collection>,
as: <output array field>
}
}
Edit 1:
You do not need to use '$lookup'
method in this case. You can simply use populate
method. Like:
Addmodule
.find({})
.populate({
path: 'chapterid',
populate: {
path: 'subjectid',
populate: { path: 'classid', model: 'Addclass' }
}
})
.exec(function(err, data) {
if (err) return handleError(err);
res.json(data);
});
or simply
Addmodule
.find({})
.populate({
path: 'chapterid.subjectid.classid',
model: 'Addclass'
})
.exec(function(err, data) {
if (err) return handleError(err);
res.json(data);
});
Because I would not suggest to use lookup if you do not merge 2 array collection (like left join in sql). I can try to add an example if you would like to see lookup version.
Upvotes: 2
Reputation: 3845
MongoDB doesn't support joins. But from version 3.2 they have added support of left outer join through $lookup operator in aggregation pipeline.
For more detailed description regarding $lookup operator please refer the documentation mentioned in following url
https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/
Upvotes: 0