0

I want to join two collections and find the documents where has one equal field and one unequal field! This is what I was tried, But not work

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 }
])
aidinMC
  • 1,415
  • 3
  • 18
  • 35

1 Answers1

0

Fields in the source document, i.e. $pID are not available inside the lookup pipeline.

In order to reference those values, you would need to define a variable using let, such as:

{
        "$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
                    }
                }
            }]
        }
    },

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

Joe
  • 25,000
  • 3
  • 22
  • 44