Negative regex filters

161 views
Skip to first unread message

Corina Ciulea

unread,
Nov 23, 2015, 4:35:14 PM11/23/15
to mongodb-user
Hi,

I am using MongoDB.Driver v2.0.1.27. Is there a way to do a negative regex query using MongoDB.Driver and FilterDefinition?

Thank you.


Wan Bachtiar

unread,
Nov 26, 2015, 2:15:03 AM11/26/15
to mongodb-user

Hi Corina,

The $not operator does not support operations with the $regex operator. Although you can use the $not operator along with // to express a not filter match.

For example to find an item value that does not start with the word ‘baco’ in MongoDB Shell:

db.collection.find( { item: { $not: /^baco/ } } );


You can achieve a similar operation in C# using FilterDefinition, for example:

/* Create a regex filter for 'text' field not starting with 'friday'*/
FilterDefinition<BsonDocument> filter = "{text: {$not: /^friday/ }}";

var collectionFilter = collection.Find(filter);
var result = await collectionFilter.ToListAsync();
foreach (BsonDocument doc in result)
{ 
    Console.WriteLine(doc.ToString()); 
}

The example snippet above is written in:

  • .Net framework v4.5.2
  • MongoDB v3.0
  • MongoDB C# driver v2.1.0

See Definitions and Builders for more information.

Regards,

Wan.

Reply all
Reply to author
Forward
0 new messages