[英]Lookup in mongodb not working when getting objects from array of objects
productId
in the wishList
is a String
, while the _id
field in product
is an ObjectId
. wishList
中的productId
是String
,而product
中的_id
字段是ObjectId
。
You can change the type of the productId
in the wishList
or you can use $lookup
with let
and pipeline
to project the _id
in product
as a String value before comparing it to wishList.productId
, like this:您可以更改
wishList
中productId
的类型,也可以使用$lookup
与let
和pipeline
将product
中的_id
投影为 String 值,然后再将其与wishList.productId
进行比较,如下所示:
{
"$lookup":
{
"from": "products",
"let":
{
"productId": "$wishList.productId"
},
"pipeline":
[
{
"$addFields":
{
"idAsString":
{
"$toString": "$_id"
}
}
},
{
"$match":
{
"$expr":
{
"$eq":
[
"$idAsString",
"$$productId"
]
}
}
}
]
}
}
I haven't tested the query, since you didn't provide an easy way to reproduce the error, as mentioned by toyota Supra in the comment to your question, but it should be something along these lines.我没有测试查询,因为您没有提供一种简单的方法来重现错误,正如丰田 Supra 在对您的问题的评论中提到的那样,但它应该是这样的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.