【发布时间】:2021-12-25 01:16:48
【问题描述】:
我需要将同一个表“实体”中的实体连接在一起。 本地键是本地实体的_id。 外键位于“rels”对象数组中(_id 存储在 rels.r 中)。
当我使用示例 _id 字符串测试 $match 时,查找工作正常。 但是当我尝试使用用'let'声明的变量时(应该使用相同的字符串,只是在一个变量中)它不起作用。
示例数据:
{ // PARENT ENTITY
"_id":"123", // the local key
"title":"initialentity",
},
{ // CHILD ENTITY
"_id":"456",
"title":"relatedentity",
"rels":[
{
"r":"123", // the foreign key
"a":"exampledata-ignorethisfield",
},
]
}
聚合:
[
{ "$lookup": {
"from": "entities",
"let": { "id": { $toString: "$_id" } },
// "let": { "id": "$_id" }, // this alternative let doesn't work either
"pipeline": [
//{ "$match": { "rels.r": "123" } }, // This test works fine
{ "$match": { "rels.r": "$$id" } }, // But this, using the let variable, doesn't work
{"$limit": 1}
],
"as": "result"
}},
{"$limit": 1}
]
实际输出(结果数组为空):
{
"_id":"123", // the local key
"title":"initialentity",
"results": []
},
预期输出(结果数组有相关对象):
{
"_id":"123", // the local key
"title":"initialentity",
"results": [
{
"_id":"456",
"title":"relatedentity",
"rels":[
{
"r":"123", // the foreign key
"a":"exampledata-ignorethisfield",
},
]
}
]
},
由于将添加其他条件,我需要它使用此方法(使用管道)。
提前感谢您的帮助。我确定我遗漏了一些明显的东西。我浏览了许多 SO qs 和 mongo 文档,但无法弄清楚这一点。 我也尝试过以下方法但没有成功:
{ "$match": { $expr: { "rels": {"r" : "$$id"} } } }, // This doesn't work (returns unrelated entities)
{ "$match": { $expr: { $eq: [ "rels.r" , "$$id" ] } } }, // This doesn't work (returns empty array)
【问题讨论】:
标签: mongodb mongodb-query aggregation-framework