Home > OS >  MongoDB: find if any field is true
MongoDB: find if any field is true

Time:10-01

I have documents structured like this. Notice that this is ONE document, not collection:

{
  "1": {
    "end_flag": false
  }
  "2": {
    "end_flag": false
  }
  ...
}

Problem: In the end, I want to count documents that have a end_flag: true in any of its fields. How can I match documents that any of X.end_flag field is true? I have tried:

[
    {
        "$match": {
            "1.end_flag": true, 
            "2.end_flag": true,
            "3.end_flag": true,
            "4.end_flag": true,
            "5.end_flag": true,
            "6.end_flag": true,
            "7.end_flag": true,
            "8.end_flag": true,
            "9.end_flag": true,
            "10.end_flag": true,
        }
    }
]

but I know this only works if all conditions are true. How can I make it any? I also tried (desperately):

[
    {
        "$match": {
         "$in": [ true, [
            "$1.end_flag", 
            "$2.end_flag",
            "$3.end_flag",
            "$4.end_flag",
            "$5.end_flag",
            "$6.end_flag",
            "$7.end_flag",
            "$8.end_flag",
            "$9.end_flag",
            "$10.end_flag"
            ] ] 
        }
    }
]

But none of them worked. I know the documents are structured poorly for this task but this is what I have.

CodePudding user response:

A- while $or operation is costly in mongodb, the best solutions is to structure your data as array like :

[
  0: {
    "number": 1
    "end_flag": false
  }
  1: {
    "number": 2
    "end_flag": true
  }
  ...
}

then you can simply query :

db.collection.find({"fieldName.end_flag":true});

this is the power of MongoDB

B- if there is no way to restructure your data, then you have to use $or operation like this :

db.collection.find({
$or:[
            {"1.end_flag": true}, 
            {"2.end_flag": true},
            {"3.end_flag": true},
            {"4.end_flag": true},
            {"5.end_flag": true},
            {"6.end_flag": true},
            {"7.end_flag": true}
]
})
  • Related