[英]mongodb - aggregate lookup without local
So I have two ObjectId
s that are in different collections, which I would like to be merged as an output. 所以我有两个不同集合的ObjectId
,我希望将它们合并为输出。 So it's like using the $lookup
function without any local fields. 所以它就像使用$lookup
函数而没有任何本地字段。 Without an aggregate I could simply do two .findOne
, but that would require two API calls (which would create two connections). 如果没有聚合,我可以简单地做两个.findOne
,但这需要两个API调用(这将创建两个连接)。 Is it possible to achieve it in one? 是否有可能在一个实现它?
So without the aggregation it would just look something like this: 因此,如果没有聚合,它将看起来像这样:
let main_document =
db.findOne({
_id: ObjectId(first)
})
let subdocument =
db.findOne({
_id: ObjectId(second)
})
main_document.subdocument = subdocument
return main_document
You can use below aggregation 您可以使用以下聚合
You don't need to specify the localField
in the newer $lookup
syntax. 您不需要在较新的$lookup
语法中指定localField
。 Just use $match
inside the sub pipeline of $lookup
aggregation 只需在$lookup
聚合的子管道中使用$match
db.main_document.aggregate([
{ "$match": { "_id": ObjectId(first) }},
{ "$lookup": {
"from": "subdocument",
"pipeline": [
{ "$match": { "_id": ObjectId(second) }},
],
"as": "subdocument"
}},
{ "$unwind": "$subdocument" }
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.