如何在对象数组mongo中查找和过滤?

时间:2019-07-26 13:36:57

标签: node.js mongodb mongoose

我对mongodb中对象的查找和过滤器数组有疑问

我有一个结构:人

{
    "_id": "5cc3366c22c3767a2b114c6b",
    "flags": [
        "5cc30210fada5d7820d03aaf",
        "5cc2c3924a94a575adbdc56a"
    ],
    "key": "Animal",
    "name": "name1",
    "description": "description1",
    "endpoints": [
        {
            "isEnabled": true,
            "publishUrl": "megaUrl",
            "env": "5cc1a8911b19026fd193506b"
        },
        {
            "isEnabled": true,
            "publishUrl": "megaUrl",
            "env": "5ccaeef3312acb103730d4c5"
        }
    ]
}

envs收藏

{
    "_id" : "5cc1a8911b19026fd193506b",
    "name" : "name2",
    "key" : "PROD",
    "publishUrl" : "url1",
    "__v" : 0
}

{
    "_id" : "5ccaeef3312acb103730d4c5",
    "name" : "name2",
    "key" : "PROD",
    "publishUrl" : "url1",
    "__v" : 0
}

我应该按端点过滤文档。$。env 因此,我有:accessKeys = ["PROD", "UAY"],我应该看到result。端点为env.key === "PROD" || env.key === "UAT"

预期结果:

{
    "_id": "5cc3366c22c3767a2b114c6b",
    "flags": [
        "5cc30210fada5d7820d03aaf",
        "5cc2c3924a94a575adbdc56a"
    ],
    "key": "Animal",
    "name": "name1",
    "description": "description1",
    "endpoints": [
        {
            "isEnabled": true,
            "publishUrl": "megaUrl",
            "env": {
                "_id" : "5cc1a8911b19026fd193506b",
                "name" : "name2",
                "key" : "PROD",
                "publishUrl" : "url1",
                "__v" : 0
            }
        },
    ]
}

请帮助我,我该怎么做?我知道聚合,但不能做到这一点:(

1 个答案:

答案 0 :(得分:1)

尝试一下:

db.persons.aggregate([{
    $unwind : "$endpoints"
},{
    $lookup :{
        from  : "envs",
        localField : "endpoints.env",
        foreignField : "_id",
        as : "endpoints.env"
    }
},{
    $unwind : "$endpoints.env"
},{
    $match : {
        "endpoints.env.key" : {$in : accessKeys}
    }
},{
    $group : {
        _id : "$_id",
        flags : {$first : "$flags"},
        key : {$first : "$key"},
        name : {$first : "$name"},
        description : {$first : "$description"},
        endpoints : {$push : "$endpoints"},
    }
}])