【问题标题】:Mongodb lookup for not equal fieldsMongodb查找不相等的字段
【发布时间】:2021-09-20 05:15:36
【问题描述】:

我想加入两个集合,找到一个相等字段和一个不相等字段的文档! 这是我尝试过的,但不起作用

db.collectionOne.aggregate[
    {
        "$match": {
            "$and": [
                { "$text": { "$search": "this is my query" } },
                { "b": { "$eq": "60e849054d2f0d409041b6a2" } }
            ]
        }
    },
    { "$addFields": { "pID": { "$toString": "$_id" }, "score": { "$meta": "textScore" } } },
    {
        "$lookup": {
            "from": "collectionsTwo",
            "as": "collectionsTwoName",
            "pipeline": [{
                "$match": {
                    "$expr": {
                        "$and": [{
                            "$ne": ["$fieldOne", "60dd0f98d10f072e2a225502"] // This one is unqual field
                        }, { "$eq": ["$pID", "$fieldTwo"] }] // This one is equal field
                    }
                }
            }]
        }
    },
    { "$sort": { "score": -1 } },
    { "$limit": 1 }
])

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework mongodb-lookup


    【解决方案1】:

    源文档中的字段,即$pID 在查找管道中不可用。

    为了引用这些值,您需要使用let 定义一个变量,例如:

    {
            "$lookup": {
                "from": "collectionsTwo",
                "as": "collectionsTwoName",
                "let": { "srcpID":"$pID" },
                "pipeline": [{
                    "$match": {
                        "$expr": {
                            "$and": [{
                                "$ne": ["$fieldOne", "60dd0f98d10f072e2a225502"] // This one is unqual field
                            }, { "$eq": ["$$srcpID", "$fieldTwo"] }] // This one is equal field
                        }
                    }
                }]
            }
        },
    

    https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/#join-conditions-and-uncorrelated-sub-queries

    【讨论】:

    • 嗨,乔感谢您的回答,实际上 "$eq": ["$pID", "$fieldTwo"] } 有效,"$ne": ["$fieldOne", "60dd0f98d10f072e2a225502"] 无效
    • 我也应该将$fieldOne 添加到let 吗?
    • 如果fieldOne属于来自collectionOne的文档,那么是的。
    • 另请注意,如果fieldOne 包含一个ObjectId,则$ne comparison 将始终匹配。
    • 不属于collectionTwo并持有String值
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 2018-10-15
    相关资源
    最近更新 更多