mongodb - Not getting correct result with aggregate and pipeline
问题描述
Having issues with using the pipeline and getting the correct data back in my aggregate query. I have two collections where they both share a common id (eventId) that I want to use to "join" these collections.
Document from collection Pool
{
"_id": ObjectId("5e1ebbc6cffd4b042fc081ab"),
"eventId": "ABC_2020-01-15_40_1",
"trackName": "Foo",
"type": "bar"
}
Document from collection Races (multiple ones with same eventID
{
"_id": ObjectId("5e1ebbc6cffd4b042fc081a1"),
"eventId": "ABC_2020-01-15_40_1",
"Data": {foo:"bar"}
}
The data I get back includes all the documents from the races collection, it seems that the pipeline is not running as I get the same result as if pass in an [] in the pipeline. I would like to getting some help figuring this out as I only want the ones with the same eventId in both collections in the result.
const result = await PoolModel.aggregate([
{
$match: {
eventId,
},
},
{
$lookup: // join two collections
{
from: 'races', // races collection
let: { eventId: '$event.eventId' }, // define vars to use in pipeline
pipeline: [
{ $match: { $expr: ['$eventId', '$$eventId'] } },
{ $project: projection },
],
as: 'races', // Display in new result as as
},
},
]);
This is my result:
result: [ { _id: 5e1ebbc6cffd4b042fc081ab,
eventId: 'ABC_2020-01-15_40_1',
trackName: 'Foo',
type: 'bar',
races:
[ [Object], // Wrong id
[Object], // Wrong id
[Object], // Wrong id
[Object], // Wrong id
[Object], // Wrong id
[Object], // Wrong id
[Object], // Wrong id
[Object], // Correct id
[Object], // Correct id
[Object], // Correct id
[Object], // Correct id
[Object], // Correct id
[Object], // Correct id
[Object], // Correct id
[Object] ] } ]
解决方案
In the pipeline on the joined collection, $expr
is expecting a conditional comparison operator (with an example to use it in a $lookup
pipeline here) and you have given it none so in essence there is no filtering going on.
You would rather use the $eq
operator as
{ '$match': { '$expr': { '$eq': ['$eventId', '$$eventId'] } } },
推荐阅读
- android - 使用合并标签时复合视图不可见
- ruby - 查找具有相同数字的下一个最小数字
- google-kubernetes-engine - GKE 上的 HAProxy 入口控制器
- c# - 在元组列表中查找具有最高 Item1 值的元组 - 然后将其从列表中删除
- reactjs - 为什么启用全屏模式后暂停会重置?
- javascript - 从 Ajax 调用返回值到 Javascript 函数
- javascript - 如何为 Forge Viewer 加载扩展(没有 viewerApp)
- junit - Spring Junit Mockito Runner 从测试应用程序属性文件中读取属性
- angular - Angular 7:npm 包中的“类”需要 polyfill
- c++ - 用大小初始化 std::vector 数组