Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo aggregation with $ne

I can't seem to find any resources at all on Mongo aggregation with the boolean operations. My query looks something like this (I am using the pymongo driver):

db.collection.aggregate([{'$match': {'foo': 3, 'bar': 'baz'}},
                          {'$project': {'quxx': 1, '_id': 0, 'count': 1}},
                          {'$group': {'total': {'$sum': '$count'}, '_id': '$quxx'}},
                          {'$sort': {'total': -1}},
                          {'$limit': 2000}])

Which all works great ($match is on an index etc). Now, there is a single rogue quxx that I would like to filter out of the pipeline so I thought that I would use the $ne operator. However, I can't seem to figure out the proper way to do it! I'm not sure if I'm not placing it at the right point (I want it after the $match operator but before the $group operator) or I have the syntax wrong but help would be appreciated.

The things I have tried so far (all in their own step after $match) are:

{'$quxx': {'$ne': 'rogue'}}
{'quxx': {'$ne': 'rogue'}}
{'$ne': {'quxx': 'rogue'}}
{'$ne': {'$quxx': 'rogue'}}

Every single one of them gives me unrecognized pipeline op.

like image 426
dreamriver Avatar asked Dec 05 '22 12:12

dreamriver


1 Answers

You would either put that in its own $match pipeline element, or just include it in the initial $match.

So either add:

{'$match': {'quxx': {'$ne': 'rogue'}}}

or modify the initial $match to:

{'$match': {'foo': 3, 'bar': 'baz', 'quxx': {'$ne': 'rogue'}}}
like image 153
JohnnyHK Avatar answered Dec 14 '22 23:12

JohnnyHK