A. L
A. L

Reputation: 12639

mongodb - aggregation with $match $in with a $lookup pipeline

If I have the following object as obj:

{
    "abc1": "xyz1",
    "abc2": "xyz2",
    "abc3": "xyz3"
}

and I want to do an aggregation with something like:

db.collection.aggregate([
    { 
        "$match": { 
            "_id": {
                $in:
                    Object.keys(obj)
            }
        } 
    },
    {
        "$lookup": {
            "from": "subdocument",
            "pipeline": [
                { 
                    "$match": { 
                        "_id": ObjectId(matching_value) 
                    } 
                },
            ],
            "as": "subdocument"
        }
    },
    { "$unwind": "$subdocument" }
])

how do I get the $lookup pipeline to match the object key to match the object value? Is it possible?

So it would be a single db call version of this:

let obj = {
    "abc1": "xyz1",
    "abc2": "xyz2",
    "abc3": "xyz3"
}

for (let key in obj)
{
    db.collection.aggregate([
        { 
            "$match": { 
                "_id": 
                    ObjectId(key)
            } 
        },
        {
            "$lookup": {
                "from": "subdocument",
                "pipeline": [
                    { 
                        "$match": { 
                            "_id": ObjectId(obj[key]) 
                        } 
                    },
                ],
                "as": "subdocument"
            }
        },
        { "$unwind": "$subdocument" }
    ])
}

Example collections

db.maindocuments
[
    {
        _id: "abc1",
        data: "data"
    },
    {
        _id: "abc2",
        data: "data"
    },
    {
        _id: "abc3",
        data: "data"
    }
]


db.subdocuments
[
    {
        _id: "xyz1",
        data: "data"
    },
    {
        _id: "xyz2",
        data: "data"
    },
    {
        _id: "xyz3",
        data: "data"
    }
]

Upvotes: 1

Views: 369

Answers (1)

Ashh
Ashh

Reputation: 46441

Well I can see there is no relation in both the collections. and that's why $lookup won't work as there is no matching keys in the documents.

Therefore, You can do using async await

const obj = {
  "abc1": "xyz1",
  "abc2": "xyz2",
  "abc3": "xyz3"
}

for (let key in obj) {
  const data = await db.collection.findOne({ _id: key })
  const subdocument = await db.subdocument.findOne({ _id: obj[key] })
  data.subdocument = subdocument
}

Upvotes: 1

Related Questions