5

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.

dreamriver
  • 1,291
  • 2
  • 15
  • 20
  • See: https://stackoverflow.com/questions/41377775/how-to-compare-two-fields-in-a-document-in-pipeline-aggregation-mongodb – Super Mario Nov 05 '19 at 13:57

1 Answers1

17

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'}}}
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • The initial match traverses a composite index and I don't want to index on quxx. Does that mean I should go with the former? – dreamriver Mar 11 '13 at 03:23
  • 1
    @dreamriver Check the modified initial match using `explain` on an identical `find` to see if your existing index is still used (I expect it would be). – JohnnyHK Mar 11 '13 at 03:25
  • See: https://stackoverflow.com/questions/41377775/how-to-compare-two-fields-in-a-document-in-pipeline-aggregation-mongodb – Super Mario Nov 05 '19 at 13:56