Query with filter builder on nested array using MongoDB C# driver
23,748
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"));
Author by
kspearrin
Updated on June 23, 2020Comments
-
kspearrin almost 4 years
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
allFoo
that contain aFooBar
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 onFind
?