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
?
Set filtering conditions for nested array in MongoDB MongoDB Database Big Data Analytics To set filtering conditions, use $ filter and $cond in MongoDB aggregate (). The $ filter selects a subset of an array to return based on the specified condition.
MongoDB provides a feature which is known as embedded or Nested document. The Embedded document or nested documents are those types of documents that contain documents inside another document.
Builders are classes provided by the MongoDB Java driver that help you construct BSON objects. To learn more, see our guide on builders. Filters are the operations MongoDB uses to limit your results to what you want to see. A hotel with amenities that include an indoor swimming pool and free parking
MongoDB provides the $ne that selects the documents where the value of the field is not equal to the defined value. This covers documents that do not contain the field. Let’s get understand this topic followed by an example.
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"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With