Search code examples
mongodbmongodb-compass

mongodb, how to use $not filter in query


I have what should be a fairly simple query I'm trying to run in mongodb compass:

{ $and: [ { Source: "hostname" }, { Message: { $not: /.*unexpected data.*1234.*/ } } ] }

Basically, my document model contains a Source field and a Message field.

I need to query for all documents where the Source equals a given "hostname" and the Message does not contain "unexpected data...1234"

Everything works fine when I DO NOT include the $not filter on the regular expression... so I get all the documents where this message is contained... but now I need all the other messages where this is NOT contained... and I can't figure out how to use $not properly.

The example given in the MongoDb manual only shows using $not with one statement... but even this doesn't work for me for some reason...

{ Message: { $not: /.*unexpected data.*1234.*/ } }

Again, it works fine without the $not... what am I missing?

Edit:

Here is an image of what I'm talking about, placing this filter in MongoDb Compass, it indicates that the filter is incorrect... Is MongoDb Compass for some reason incapable of running complex filters? broken mongo filter


Solution

  • enter image description herePlease try with $regex which should work:

    find( { $and: [ { Source: "hostname" }, { Message: { $not: { $regex: /.*unexpected data.*1234.*/ } } } ] })