Basics
Meet the builder π€
Filter Definition Builder
To create a filter query for an IMongoCollection<T>
collection, you need to build a FilterDefinition<T>
filter. You can do this using the Builders<T>.Filter
filter definition builder which contains several filters such as the equality or element filters. This section will give you an overview on how to create and use the filter definition builder.
The Empty
filter
Empty
filterUse the Empty
filter when you want to get either the 1st document or all of its documents.
When querying a IMongoCollection<BsonDocument>
collection, you can use an empty BsonDocument
as an empty filter definition
Equality filter on a top level field
The equality filter is one of the most used filters you are gonna use when querying MongoDB. The following examples filter user documents on top level string fields, profession and email.
Equality filter is case sensitive, so always make sure to use it properly!
Equality filter on a nested field
You can use the equality filter to match your documents based on an embedded document field. In the following example the address field is an embedded field on the user document and contains a city string field. The sample show how to filter documents based on the city field.
The hierarchy from <field1>
to the <embedded-field>
cannot contain an array field
Remember, the filter might be on an embedded document field, but the result will be always the entire document(s) that matched the criteria
Equality filter on a array field
Assuming your document contains an array field with string values, you want to get all documents that their array field contains a specific value. The sample that follows works for other types as well (e.g. bool, int, decimal, float).
The example retrieves all user documents that their FavoriteSports array field contains a specific sport. It does that by using an equality filter for an array field called AnyEq
.
When the search term used in AnyEq
is a simple value, then you are running a search for that term in the array field, meaning that there might be other values contained as well
Equality filter on a array field - Exact match
In case you want to run an exact match on the array field then you must use an array argument in the AnyEq
filter. This will try match the entire array field rather than just searching inside the array.
The following example finds the documents that their FavoriteSports array field contains only the Soccer term.
Last updated