Jackson
Jackson

Reputation: 914

How to lookup and filter in array of objects mongo?

I have a question about lookup and filter array of objects in mongodb

I have structure: Person

{
    "_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 collection

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

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

I should filter Document by endpoints.$.env so, I have: accessKeys = ["PROD", "UAY"], and i should see result . with endpoints where env.key === "PROD" || env.key === "UAT"

Expected result:

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

Help me pls, how i can do that? I know about aggregate, but cant do it :(

Upvotes: 0

Views: 133

Answers (1)

Ravi Shankar Bharti
Ravi Shankar Bharti

Reputation: 9268

Try this :

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

Upvotes: 1

Related Questions