我想从collection1一直查找到collection 3和collection 4,以便在一个查询中比较名称。
示例:
collection1.find({
collection2.collection3.name: req.body.name3,
collection2.collection4.name: req.body.name4
}).exec()
答案 0 :(得分:5)
您需要使用查找,展开和匹配,这是未经测试的问题解决方案
Model.aggregate([
{
$match: {
_id: req.params.id
// for object id use
// _id: mongoose.Types.ObjectId(req.params.id)
}
},
{
$lookup: {
from: "collection2",
localField: "collection2",
foreignField: "_id",
as: "Collection2"
}
},
{
$unwind: "$ColelctionTwo"
},
{
$lookup: {
from: "collection3",
localField: "CollectionTwo.collection3",
foreignField: "_id",
as: "Collection3"
}
},
{
$lookup: {
from: "collection4",
localField: "CollectionTwo.collection4",
foreignField: "_id",
as: "Collection4"
}
}
]).exec(function(err, result) {
if(err) {
// handle here
}
if(result) {
// do something here...
}
}
答案 1 :(得分:1)
您可以使用mongodb聚合框架的$lookup或$graphlookup阶段进行多集合查询。汇总https://mongoosejs.com/docs/api.html#Aggregate的猫鼬文档 您无法对多馆藏查询进行简单的查找查询。