Search code examples
mongodbmongodb-queryaggregation-frameworkmongodb-shell

By using $cond to determine something, but why $cond is always true?


  1. I was trying to find the total number of the document that does not contain both fields filed key and low. But it always returns true and the result is the total number of documents. it does exist such documents do not contain both fields.

  2. Here is the code I tried:

     db.test.aggregate([
    { "$group": {
             "_id" : { user_id: "$id" },
              "a": { 
                "$sum": {
    
            "$cond": [ {
            $and:[{low:null},{ key:null}]
            } , 1, 0
            ]
         } 
         },
    
       "b": { "$sum": {
                 "$cond": [ { "$ifNull": ["$key", false] }, 1, 0 ]
             } },
             "c": { "$sum": {
                 "$cond": [ { "$ifNull": ["$low", false] }, 1, 0 ]
             } },
           } },
           { "$project": {
             "_id": 0,
             "a": 1,
             "b": 1,
             "c": 1
           } }
            ])
    

Solution

  • Inside the $cond expression you need to use aggregation operators, not query syntax.

    Instead of {low:null} use {$eq:["$low",null]}, and likewise for the key test.