1

I'm trying to query a collection and filter based on values nested within an array and a second array using elemMatch.

{
"email": "[email protected]",
"project" [ {
                projectId: ObjectId("123"),
                preference: [
                            {"name": "name1", "value": true},
                            {"name": "name2", "value": false}
                ]
            }, 
            {
                projectId: ObjectId("456"),
                preference: [
                            {"name": "name1", "value": true},
                            {"name": "name2", "value": true}
                ]
            }
]
}, 
{
"email": "[email protected]",
"project" [ {
                projectId: ObjectId("123"),
                preference: [
                            {"name": "name1", "value": false},
                            {"name": "name2", "value": true}
                ]
            }, 
            {
                projectId: ObjectId("456"),
                preference: [
                            {"name": "name1", "value": true},
                            {"name": "name2", "value": true}
                ]
            }
]
}

I've tried a few different variations of merging the below two queries into one to try and achieve my goal of returning.

{email: "[email protected]"}

db.user.find({"project":{"$elemMatch":{"projectId":ObjectId("123")}}}, {email: 1})
db.user.find({"project.preference":{"$elemMatch":{"$and":[{"name":"name1"}, {"value": true}]}}}, {email: 1})

1 Answer 1

1

You can use $unwind to simplify querying multiple levels of nested arrays, try:

db.user.aggregate([
    {  $unwind: "$project" },
    {  $match: { "project.projectId": "123" } },
    {  $unwind: "$project.preference" },
    {  $match: { "project.preference.name": "name1", "project.preference.value": true } },
    {  $project: { _id: 0, email: 1 } }
])
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.