Home > Back-end >  MongoDB aggregation pipeline to find boolean value
MongoDB aggregation pipeline to find boolean value

Time:04-23

I wish to find out all the matching documents in a collection for which the MatchCondition is false. I am trying to do this in the aggregate pipeline using match operator but that is not working.

{
    "_id": {
        "$oid": "98rr6c03a82b7785f372c018"
    },
    "document": "DocumentName",
    "ecuCheckResultList": [
      {
        "animal": "CAT",
        "attribute1": "value",
        "attribute2": "value",
        "MatchCondition": true
      },
      {
        "animal": "DOG",
        "attribute1": "value",
        "MatchCondition": false
      }
    ]
  }

I am aware that there are options to do this using find, but there are separate operations which need to take place on this data, so using aggregate pipeline.

In the end, I need to find out the total counts of each animal within the collection that are having MatchCondition = false

There are more than 1.9 million documents within my collection on which I want to query this data.

CodePudding user response:

You can $map to construct an auxiliary boolean array to check whether the MatchCondition is false. For your case, a simple $not will work as it can flip the false to true. Afterwards, use $anyElementTrue to perform the filtering.

db.collection.aggregate([
  {
    "$match": {
      $expr: {
        "$anyElementTrue": {
          "$map": {
            "input": "$ecuCheckResultList.MatchCondition",
            "as": "mc",
            "in": {
              $not: "$$mc"
            }
          }
        }
      }
    }
  }
])

Here is the Mongo playground for your reference.

CodePudding user response:

Query1

  • unwind replace root to make each member a root document
  • match the condition to be false
  • group by anima and count

Playmongo
(for in/out of each stage you can place the mouse on the end of the stage)

aggregate(
[{"$unwind": "$ecuCheckResultList"},
 {"$replaceRoot": {"newRoot": "$ecuCheckResultList"}},
 {"$match": {"$expr": {"$eq": ["$MatchCondition", false]}}},
 {"$group": {"_id": "$animal", "count": {"$sum": 1}}}])

Query2

  • same as the above but filter first to keep only the condition false and unwind after

*probably faster from the previous

Playmongo

aggregate(
[{"$set": 
   {"ecuCheckResultList": 
     {"$filter": 
       {"input": "$ecuCheckResultList",
        "cond": {"$eq": ["$$this.MatchCondition", false]}}}}},
 {"$unwind": "$ecuCheckResultList"},
 {"$group": {"_id": "$ecuCheckResultList.animal", "count": {"$sum": 1}}}])
  • Related