猫鼬与第三级嵌套字段值进行比较
Mongoose compare with a third level nested field value
我有以下 collections:
我想从 collection1 一直到 collection 3 和 4 进行查找,以便在一个查询中比较名称。
示例:
collection1.find({
collection2.collection3.name: req.body.name3,
collection2.collection4.name: req.body.name4
}).exec()
您可以使用 mongodb 聚合框架的 $lookup or $graphlookup stages for multi collection queries. Mongoose docs for aggregation https://mongoosejs.com/docs/api.html#Aggregate
您不能对多集合查找执行简单的查找查询。
需要使用lookup、unwind和match,这里是未经测试的解决方案你的问题
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...
}
}
我有以下 collections:
我想从 collection1 一直到 collection 3 和 4 进行查找,以便在一个查询中比较名称。
示例:
collection1.find({
collection2.collection3.name: req.body.name3,
collection2.collection4.name: req.body.name4
}).exec()
您可以使用 mongodb 聚合框架的 $lookup or $graphlookup stages for multi collection queries. Mongoose docs for aggregation https://mongoosejs.com/docs/api.html#Aggregate 您不能对多集合查找执行简单的查找查询。
需要使用lookup、unwind和match,这里是未经测试的解决方案你的问题
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...
}
}