3

Say you have the following line of code:

var filter = Builders<BsonDocument>.Filter.Where(t => t.id == myId);
var result = collection.Find(filter).ToList();

Does the filter builder translate the lambda to a literal $where clause or does it optimize it to use the $eq clause? $where has slow performance so I don't want to use it if there's no translation.

This is a simple example but we have other queries in our code that are lengthier but would easily translate to non-$where queries.

1 Answers1

4

Thanks to David Osborne's comments above, I was able to do a little more research and come up with an answer. It turns out simple LINQ queries do in fact translate directly to native Mongo queries and not to $where queries.

var filter = Builders<BsonDocument>.Filter.Where(x => x["status"] != "ready");
var findFluent = collection.Find(filter);

Console.WriteLine(findFluent);

filter = Builders<BsonDocument>.Filter.Ne("status", "ready");
var findFluent = collection.Find(filter);

Console.WriteLine(findFluent);

Both print out the identical queries. This holds for simple combinations of equality and logical operators.

However, some operators appear to be inaccessible through LINQ. I attempted to write an $in query

var success = new List<string> { "imported", "processed" };
var filter = Builders<BsonDocument>.Filter.Where(x => success.Contains(x["status"].ToString()));

and got a runtime error. Similarly with a regex match

var regex = new Regex("^*0000");
var filter = Builders<BsonDocument>.Filter.Where(x => regex.IsMatch(x["orderId"].ToString()));

Not surprising but good to know.