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))
.FirstOrDefault();
Will it be correctly translated and filtered on the database side?
I just printed the query variable to view the actual query using Console.WriteLine(query);orConsole.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):