[英]MongoDB lookup by _id with let does not work
I'm using a aggregate query to retrieve data from multiple collections, however there is a strange behavior that I dont seem to understand.我正在使用聚合查询从多个 collections 中检索数据,但是有一个我似乎不理解的奇怪行为。
I need to lookup throw two collections, thus the lookup inside the pipeline.我需要查找抛出两个 collections,从而在管道内查找。 And also use the
_id
from the collection I'm making the aggregation(campaignadgroups) to match on the second nested collection (broadcastplans)并且还使用集合中的
_id
我正在聚合(campaignadgroups)以匹配第二个嵌套集合(广播计划)
This is my query:这是我的查询:
db.getCollection('campaignadgroups').aggregate([
{
$match: { "campaign_id": ObjectId("5fc8f7125148d7d0a19dcbcb")} // hardcoded just for tests
},
{
$lookup: {
from: "broadcastreports",
let: {campaignadgroupid: "$_id"},
pipeline: [
{
$match: {"reported_at": { $gte:ISODate("2020-12-01T15:56:58.743Z"), $lte: ISODate("2020-12-03T15:56:58.743Z")} }
},
{
$lookup: {
from: "broadcastplans",
localField: "broadcast_plan_id",
foreignField: "_id",
as: "broadcastplan"
}
},
{$unwind: "$broadcastplan"},
{
$match: { "broadcastplan.campaign_ad_group_id": {$eq: "$$campaignadgroupid"} // The problem happens here
}
}
],
as: "report"
}
},
])
The issue is that by matching with $$campaignadgroupid
the report documents is empty.问题是通过匹配
$$campaignadgroupid
报告文档是空的。
However, if I replace the variable with the hardcoded id like ObjectId("5fc8f7275148d7d0a19dcbcc")
I get the documents that I pretend.但是,如果我用像
ObjectId("5fc8f7275148d7d0a19dcbcc")
这样的硬编码 id 替换变量,我会得到我假装的文件。
For reference I'm debugging this issue on Robot3T so I can then translate to mongoose later.作为参考,我正在 Robot3T 上调试此问题,以便稍后转换为 mongoose。
I tried already to use $toObjectId
however the _ids
are not strings but ObjectIds
already.我已经尝试使用
$toObjectId
但是_ids
不是字符串而是ObjectIds
已经。
Thank you very much非常感谢
Ok this is why I love and hate to code.好的,这就是我喜欢和讨厌编码的原因。 After 3h debugging after asking here I immediately discovered the issue... I just needed to change from
在这里询问后 3 小时调试后,我立即发现了问题......我只需要从
$match: { "broadcastplan.campaign_ad_group_id": {$eq: "$$campaignadgroupid"}
to至
$match: { $expr: { $eq: ["$broadcastplan.campaign_ad_group_id", "$$campaignadgroupid"]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.