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

141
Views
How do I return a document with filtered sub-documents using Mongo.Driver.Linq with the Mongo C# driver 2.3?

Given the following, how do I return all the Foos that contain Bars that have TypeOfBar == "Big" and have the Foos' Bars be limited to only those Bars that have TypeOfBar == "Big" as well?

public class Foo
{
    public string _id { get; set; }
    public List<Bar> Bars { get; set; }
}

public class Bar
{
    public string _id { get; set; }
    public string TypeOfBar { get; set; }
}

I can easily get the first part (all Foos with Bars of a particular type):

var client = new MongoClient("myconnectionstring");
var db = client.GetDatabase("myDb");
var collection = db.GetCollection<Foo>("Foos");

var foos = collection.AsQueryable().Where(x => x.Bars.Any(b => b.TypeOfBar == "Big"));

However, I'm having a hard time figuring out how to also have the db return the Foos with a filtered list of Bars.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

If you want to filter out only this Foos that have type "Big" you should apply ElemMatch Projection:

var res = collection.Find(x => x.Bars.Any(b => b.TypeOfBar == "Big"))
    .Project(Builders<Foo>.Projection.ElemMatch(x=>x.Bars, b=>b.TypeOfBar == "Big"));

The problem you will have with it: Projection will return BSon. Perhaps that is what you need and you could live with it, if not, you shuold deserialize Bson to your Foo class. Complete query i did look like:

var res = collection.Find(x => x.Bars.Any(b => b.TypeOfBar == "Big"))
    .Project(Builders<Foo>.Projection.ElemMatch(x=>x.Bars, b=>b.TypeOfBar == "Big"))
    .ToEnumerable()
    .Select(b=>BsonSerializer.Deserialize<Foo>(b))
    .ToList();
over 4 years ago · Santiago Trujillo Report
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!