Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

317
Views
C# Mongo Driver: How to query list of lists?

I have two objects

public class ParentObject
{
    [BsonId]
    public Guid Id { get; set; }
    public List<ChildObject> ChildObjects{ get; set; }
}

public class ChildObject
{
    public DateTime DateTime { get; set; }
    public string Message{ get; set; }
}

I want to write a query that will find ParentObject in monogo db with the specific Id order all ChildObjects that are inside of the ParentObject based on ChildObject.DateTime and return first 10 ChildObjects. How to write it so it runs on the server-side? The important thing is that I want to avoid downloading all child ChildObjects to the client.

I wrote this query, but according to the documentation it is run on the client-side which I want to avoid

var result = mongoDb.Collection
                .Find(x=> x.Id == request.Id)
                 .Project(x => x.ChildObjects.OrderBy(c => c.DateTime).Take(10))
                 .FirstOrDefault();

I also tried LINQ but it can not be translated due to unsupported expression tree:

            var result = mongoDb.Collection.AsQueryable()
                .Where(x => x.Id== request.Id)
                .Select(x => x.ChildObjects.OrderBy(c => c.DateTime).Take(10))
            .FirstOrDefault();

The Error Message: System.NotSupportedException : The method OrderBy is not supported in the expression tree: {document}{ChildObjects}.OrderBy(c => c.DateTime).

How to write this query? And how to make sure that it is running on the server-side? Is there a possibility to see the translated query?

over 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!