0

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 :(

2
  • Could you show your query Commented Jul 26, 2019 at 13:38
  • jsfiddle.net/rnwcdpyh Commented Jul 26, 2019 at 13:44

1 Answer 1

1

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"},
    }
}])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.