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

28.3k views Asked by At

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?

1

There are 1 answers

6
i3arnon On BEST ANSWER

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"));