简体   繁体   English

从对象数组中获取对象时,mongodb 中的查找不起作用

[英]Lookup in mongodb not working when getting objects from array of objects

Wishlist product愿望清单产品

My code我的代码

Getting Wishlist Blanked.清除愿望清单。 please help me why wishlist array shows no data请帮助我为什么愿望清单数组没有显示数据

productId in the wishList is a String , while the _id field in product is an ObjectId . wishList中的productIdString ,而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:您可以更改wishListproductId的类型,也可以使用$lookupletpipelineproduct中的_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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM