查找管道,不指定localfield和foreignfield


db.Products.aggregate([
{
$lookup: {
from: "Products_History",
localField: "_fid",
foreignField: "_fid",
as: "joins",
pipeline: [
{
"$sort": {
"date": -1
}
}
]
}
},
{
"$project": {
"_fid": 1,
"field1": 1,
"field2": 1,
"field3": 1,
"last_version": {
$first: "$joins.version"
}
}
},
{
$match: {
"last_version": {
$exists: true
}
}
}
])

当MongoDB是版本5或更高版本时,这工作得很好。

然而,在我当前的版本中,我得到:"$lookup with 'pipeline'可能没有指定'localField'或'foreignField'">

是否有一种方法来修复查询,而仍然加入他们。我不知道还有什么别的办法。

https://mongoplayground.net/p/SYsmjYjOdNJ

你可以使用传统的"let "语法。在$let子句中,f被设置为一个变量,用来指代Products文档中的_fid字段。因此,查询将Products._fidProducts_History._fid(由$_fid引用)进行匹配。

db.Products.aggregate([
{
$lookup: {
from: "Products_History",
"let": {
f: "$_fid"
},
as: "joins",
pipeline: [
{
$match: {
$expr: {
$eq: [
"$$f",
"$_fid"
]
}
}
},
{
"$sort": {
"date": -1
}
}
]
}
},
{
"$project": {
"_fid": 1,
"field1": 1,
"field2": 1,
"field3": 1,
"last_version": {
$first: "$joins.version"
}
}
},
{
$match: {
"last_version": {
$exists: true
}
}
}
])

Mongo操场

最新更新