Using $nin in $cond using aggregate() function.

1,996 views
Skip to first unread message

Nisrina Luthfiyati

unread,
Mar 26, 2015, 2:05:14 PM3/26/15
to mongod...@googlegroups.com
Hi all,
I'm trying to write a query that count the number of document that pass a condition using the aggregate function.
Is there any way to use $nin or something of its equivalent in the condition? Like:

db.collectionName.aggregate({
  $group: {
    _id
: "$field1",
   
...,
    count
: {
      $sum
: {
       
$cond: [ { "$field2": {$nin: ["possibleValue1", "possibleValue2"]} }, 1, 0 ]
     
}
   
},
   
...
 
}
})


According to http://docs.mongodb.org/manual/meta/aggregation-quick-reference/#comparison-expressions $nin is not one of the comparison expressions defined in aggregation framework.

If so is there anything that I can do to accomplish the same thing while still using aggregate?
I can't put the condition in $match because I might use the documents not passing the condition in other stages.

Thank you,
Nisrina.

Will Berkeley

unread,
Mar 26, 2015, 2:50:13 PM3/26/15
to mongod...@googlegroups.com
$nin means "not having any of these values", which is the same as $and'ing together $ne expressions. Try

db.collectionName.aggregate([
 
{ "$group" : {
   
"_id" : "$field1",

   
"count" : {
     
"$sum" : {
       
"$cond" : [ { "$and" : [{ "$ne" : [ "$field2", "possibleValue1" ] }, { "$ne" : [ "$field2", "possibleValue2" ] } ] }, 1, 0 ]
     
}
   
}
 
} }
])

There were also some syntax errors in the pipeline. I fixed them.

-Will

Nisrina Luthfiyati

unread,
Mar 27, 2015, 4:04:25 AM3/27/15
to mongod...@googlegroups.com
Hi Will,
ah that sounds so obvious now why didn't I think of that.

Thank you!
Nisrina
Reply all
Reply to author
Forward
0 new messages