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.
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 } } ])
Asked
Active
Viewed 551 times
0

Jay Park
- 308
- 1
- 6
- 14
1 Answers
1
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.

Joe
- 25,000
- 3
- 22
- 44
-
Thank you. I just follow your steps but why the output becomes zero for a. – Jay Park Sep 10 '20 at 08:13
-
Without seeing any data, I have no idea. – Joe Sep 10 '20 at 08:14
-
The query appears to work in the [playground](https://mongoplayground.net/p/l2w1i3aeRyV) – Joe Sep 10 '20 at 08:21