请尝试以下查询:
db.document.aggregate([
{
$lookup:
{
from: "parameter",
let: { type: "$type", status: "$status" },
pipeline: [
{ $match:
{ $expr:
{ $and:
[
{ $eq: [ "$parameter", "example" ] },
{ $eq: [ "$type", "$$type" ] },
{ $eq: [ "$status", "$$status" ] }
]
}
}
}
],
as: "documentParameterJoined"
}
}
])
文档收集数据:
/* 1 */
{
"_id" : ObjectId("5e160929627ef782360f69aa"),
"status" : "mystatus",
"type" : "whattype"
}
/* 2 */
{
"_id" : ObjectId("5e160931627ef782360f6abb"),
"status" : "mystatus1",
"type" : "whattype1"
}
参数收集数据:
/* 1 */
{
"_id" : ObjectId("5e16095f627ef782360f6e1d"),
"parameter" : "example",
"status" : "mystatus",
"type" : "whattype"
}
/* 2 */
{
"_id" : ObjectId("5e16097e627ef782360f70b5"),
"parameter" : "example",
"status" : "mystatus1",
"type" : "whattype1"
}
/* 3 */
{
"_id" : ObjectId("5e160985627ef782360f7152"),
"parameter" : "example1",
"status" : "mystatus",
"type" : "whatType"
}
/* 4 */
{
"_id" : ObjectId("5e160a39627ef782360f8027"),
"parameter" : "example",
"status" : "mystatus1",
"type" : "whatType"
}
/* 5 */
{
"_id" : ObjectId("5e160a42627ef782360f80ec"),
"parameter" : "example",
"status" : "mystatus",
"type" : "whatType1"
}
结果:
// You don't see docs 3 to 5 as they don't match any filter criteria.
/* 1 */
{
"_id" : ObjectId("5e160929627ef782360f69aa"),
"status" : "mystatus",
"type" : "whattype",
"documentParameterJoined" : [
{
"_id" : ObjectId("5e16095f627ef782360f6e1d"),
"parameter" : "example",
"status" : "mystatus",
"type" : "whattype"
}
]
}
/* 2 */
{
"_id" : ObjectId("5e160931627ef782360f6abb"),
"status" : "mystatus1",
"type" : "whattype1",
"documentParameterJoined" : [
{
"_id" : ObjectId("5e16097e627ef782360f70b5"),
"parameter" : "example",
"status" : "mystatus1",
"type" : "whattype1"
}
]
}
您不需要进行两次数据库调用,您可以使用$lookup(mongoDB 原生)和表达式来实现所需。您也可以尝试使用mongoose populate 进行类似操作(这是对 mongoDB $lookup 的一种包装器)
参考: $lookup , mongoose-populate