1

Let say I have the following collection named survey:

{ _id: 1, results: [ { product: "abc", active: true}, { product: "xyz", active: true} ] }
{ _id: 2, results: [ { product: "abc", active: false }, { product: "xyz", active: true } ] }
{ _id: 3, results: [ { product: "abc", active: false }, { product: "xyz", active: false } ] }

by doing:

db.survey.find(
   { results: { $elemMatch: { active:  false } }
)

I will get all the docs where at least one object in the array is false i.e.

{ _id: 2, results: [ { product: "abc", active: false }, { product: "xyz", active: true } ] }

{ _id: 3, results: [ { product: "abc", active: false }, { product: "xyz", active: false } ] }

but how can I get only those docs which has all the key active: false i.e:

{ _id: 3, results: [ { product: "abc", active: false }, { product: "xyz", active: false } ] }

TIA..

0

so here I got one solution, which is perfectly apt for my need:

db.getCollection('survey').aggregate([
    { "$match": { "results.active": false } },
    { "$redact": {
        "$cond": {
            "if": {
                "$allElementsTrue": {
                    "$map": {
                        "input": "$results",
                        "as": "result",
                        "in": { "$eq": [ "$$result.active", false ] }
                    }
                }               
            },
            "then": "$$KEEP",
            "else": "$$PRUNE"
        }
    }}    
])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.