0

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

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 }
])
4

1 回答 1

0

源文档中的字段,即$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

于 2021-07-10T00:20:05.960 回答