eerick
eerick

Reputation: 447

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

Upvotes: 1

Views: 6153

Answers (2)

blakemade
blakemade

Reputation: 107

MongoDB Compass only supports regex surrounded by single quotes, not forward slashes. So $regex: /.*unexpected data.*1234.*/ should be $regex: '.*unexpected data.*1234.*'.

https://jira.mongodb.org/browse/COMPASS-2993

Upvotes: 0

Dexter
Dexter

Reputation: 982

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

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

Upvotes: 4

Related Questions