Query with filter builder on nested array using MongoDB C# driver

kspearrin picture kspearrin · Jun 22, 2015 · Viewed 18.2k times · Source

Consider the following object structure stored as documents:

public class Foo
{
    public string Id { get; set; }
    public ICollection<FooBar> Bars { get; set; }

    // ...
}

public class FooBar
{
    public string BarId { get; set; }

    // ...
}

Using a LINQ-style query with the driver I can Find all Foo that contain a FooBar BarId like this:

var foos = await m_fooCollection.Find( f => f.Bars.Any( fb => fb.BarId == "123") ).ToListAsync();

How can I achieve this same query using the FilterDefinitionBuilder instead of the in-line LINQ on Find?

Answer

i3arnon picture i3arnon · Jun 22, 2015

The query you need to perform uses the $elemMatch query operator.

So, this query using a lambda expression

var findFluent = collection.Find(f => f.Bars.Any(fb => fb.BarId == "123"));

Is equivalent to this query using the FilterDefinitionBuilder:

var findFluent = collection.Find(Builders<Foo>.Filter.ElemMatch(
    foo => foo.Bars, 
    foobar => foobar.BarId == "123"));