How to make sure that LINQ query is performed on database side?

I am using MONGODB .NET DRIVER to write a query using LINQ and I am wondering how to make sure that the query was correctly translated and performed on the database side instead of downloading unnecessary data to memory and applying a filter afterward?

The best option would be to see the translated query. Is there any way to see it?

This is an example of the query that I’m building. I have a list of objects (let’s call it parent object) where each parent object contains a very large list of o child objects. My goal is to order child objects inside each parent object and take e.g. first 100 child objects. The sorting order can vary. My current solution:

            var query = _testResourcesDb.Collection.AsQueryable()
            .Where(x => x.TestId == request.TestId)
            .Select(x => x.Logs);

        var orderedQuery = pagingParams.Sort switch {
            SortOrdering.Ascending => query.Select(x => x.OrderBy(tl => tl.DateTime)),
            SortOrdering.Descending => query.Select(x => x.OrderByDescending(tl => tl.DateTime)),
            _ => throw new ArgumentOutOfRangeException()

        var result = orderedQuery.Select(x => x.Skip(skip).Take(take))

Will it be correctly translated and filtered on the database side?

Hello @Martin_Horak, welcome to the MongoDB Community forum!

In general, any code that is accessing the database needs to be tested before using it in production. The same applies here also.

If you want to know the actual query that is executed on the server for the LINQ query, you can view it by printing the query.

For example, consider the following LINQ query:

var query = collection.AsQueryable()
                       .Where<Book>(b => == "Mark Twain")
                       .Select(b => b.title);

I just printed the query variable to view the actual query using Console.WriteLine(query); or Console.WriteLine(query.GetExecutionModel());. The output I got was this (the actual query, an aggregate with match and project stages which is what the LINQ’s Where and Select correspond to respectively):

aggregate([{ "$match" : { "author" : "Mark Twain" } }, { "$project" : { "title" : "$title", "_id" : 0 } }])

Here a post about Linq queries, which explains how the output of the query can be printed or viewed: