Skip to content

Instantly share code, notes, and snippets.

@rajeshpv
Created January 14, 2025 18:43
Show Gist options
  • Select an option

  • Save rajeshpv/6ae1f4f7627ecb5ed5d1aaf76f359451 to your computer and use it in GitHub Desktop.

Select an option

Save rajeshpv/6ae1f4f7627ecb5ed5d1aaf76f359451 to your computer and use it in GitHub Desktop.
db.collectionA.insertMany([
    { "_id": 1, "field1A": "A", "field2A": 100 },
    { "_id": 2, "field1A": "B", "field2A": 200 }

]);

db.collectionB.insertMany([
    { "_id": 1, "field1B": "A", "field2B": 100 },
    { "_id": 2, "field1B": "C", "field2B": 300 }
]);


db.collectionA.aggregate([
    {
        $lookup: {
            from: "collectionB", // Target collection
            let: { fieldLeft1: "$field1A", fieldLeft2: "$field2A" }, // Fields from collectionA
            pipeline: [
                {
                    $match: {
                        $expr: {
                            $and: [
                                { $eq: ["$field1B", "$$fieldLeft1"] }, // Match field1
                                { $eq: ["$field2B", "$$fieldLeft2"] }  // Match field2
                            ]
                        }
                    }
                }
            ],
            as: "matchedData" // Output array field in collectionA
        }
    }
]);
@rajeshpv
Copy link
Author

rajeshpv commented Jan 14, 2025

Result would be, notice matchedData with array of 1 and 0 records

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment