Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query with filter builder 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-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?

like image 495
kspearrin Avatar asked Jun 22 '15 17:06

kspearrin


People also ask

How to set filtering conditions for nested array in MongoDB?

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.

What is embedded or nested document in MongoDB?

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.

What is the difference between a builder and a filter?

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

What is $NE in MongoDB?

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.


1 Answers

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"));
like image 67
i3arnon Avatar answered Sep 20 '22 06:09

i3arnon