Query with filter creator on nested array using MongoDB C # driver
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 type query with a driver, I can Find
all Foo
that contains 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 FilterDefinitionBuilder
inline LINQ instead of Find
?
source to share
The query to be executed uses the query statement $elemMatch
.
So this query using lambda expression
var findFluent = collection.Find(f => f.Bars.Any(fb => fb.BarId == "123"));
Is equivalent to this query with FilterDefinitionBuilder
:
var findFluent = collection.Find(Builders<Foo>.Filter.ElemMatch(
foo => foo.Bars,
foobar => foobar.BarId == "123"));
source to share