mongodb-使用$ lookup管道使用$ match $ in进行聚合

时间:2019-02-02 13:59:06

标签: javascript mongodb

如果我有以下对象作为obj

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

我想用类似的东西进行聚合:

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

如何获取$lookup管道以匹配对象键以匹配对象值?有可能吗?

因此它将是单个数据库调用版本:

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

示例收藏

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"
    }
]

1 个答案:

答案 0 :(得分:1)

好吧,我看到两个集合都没有关系。这就是$lookup无法使用的原因,因为文档中没有匹配的键。

因此,您可以使用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
}