Difference between about c# expression query syntax and bson query syntax

Hi,

This document only mentioned the bson query syntax and the bson query builder when programming in c#. I assume the bson query and the bson query builder are equivalent.

In c#, the API also allows us to use the expression query syntax, e.g.:

db.data.FindAsync(d => d.Field == "a");

I want to ask if the API will translate the expression syntax into bson and then send it to the server, or if it pulls all the data to the client and then performs the filtering.

Hi, @Xi_Shen,

Welcome to the MongoDB Community Forums.

You are correct that you can specify queries in the .NET/C# driver using a variety of syntactic options including builders and expressions. The query is translated into MQL and sent to the server as BSON. The driver never performs in-memory filtering/sorting unless you explicitly call ToList (or similar method) and then use LINQ-to-Objects on the returned IEnumerable<T>.

var query = coll.AsQueryable().Where(d => d.Field == "a"); // will generate MQL
var results = query.ToList(); // now you're dealing with an IEnumerable<T> in memory
var filtered = results.Where(d => d.AnotherField == 42); // LINQ-to-Objects

You can use the MongoDB Analyzer for .NET to visualize the generated MQL for Builder and LINQ queries in Visual Studio and JetBrains Rider. In many cases, you can also call ToString() on a query to display the generated MQL:

var query = coll.AsQueryable().Where(d => d.Field == "a");
Console.WriteLine(query.ToString());

Output:

aggregate([{ "$match" : { "Field" : "a" } }])

Sincerely,
James

1 Like