Create a Query Filter

For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt

Create a Query Filter

Overview

In this guide, you can learn how to use the MongoDB .NET/C# Driver to create a query filter. A query filter is an expression that specifies the documents to read, update, or delete in a CRUD operation. You can use builder methods, available from the Builders<TDocument>.Filter static property, to create query filters and add operations to them.

Note: Method Overloads

Many of the methods on this page have multiple overloads. The examples in this guide show only one definition of each method. For more information about the available overloads, see the API documentation.

Important: Input Validation

Builder classes and LINQ queries pass values to the underlying MongoDB operation. By design, these APIs are not a security sanitization layer. Validate and sanitize untrusted input in your application before you pass it to a builder or a LINQ query.

Sample Data

The examples in this guide use the following documents in a collection called guitars:

{ "_id": 1, "make": "Fender", "models": ["Stratocaster", "Telecaster"], "establishedYear": 1946, "rating": 9 }
{ "_id": 2, "make": "Gibson", "models": ["Les Paul", "SG", "Explorer"], "establishedYear": 1902, "rating": 8 }
{ "_id": 3, "make": "PRS", "models": ["Silver Sky", "SE", "Custom"], "establishedYear": 1985, "rating": 9 }
{ "_id": 4, "make": "Kiesel", "models": ["Ares", "Vader", "Solo"], "establishedYear": 2015 }
{ "_id": 5, "make": "Ibanez", "models": ["RG", "AZ"], "establishedYear": 1957, "rating": 7 }
{ "_id": 6, "make": "Strandberg", "models": ["Boden", "Salen"], "establishedYear": 1982 }

The following Guitar class models the documents in this collection:

public class Guitar
{
    public int Id { get; set; }

    public string Make { get; set; }

    public List<string> Models { get; set; }

    public int EstablishedYear { get; set; }

    public int? Rating { get; set; }
}

To run the code examples on this page, you must obtain a reference to the guitars collection, as shown in the following example:

var client = new MongoClient("localhost://27017");
var guitarCollection = client.GetDatabase("example").GetCollection<Guitar>("guitars");

Note:

The documents in the guitars collection use the camel-case naming convention. The examples in this guide use a ConventionPack to deserialize the fields in the collection into Pascal case and map them to the properties in the Guitar class.

To learn more creating and serializing custom classes, see the following pages:

  • [POCOs](https://www.mongodb.com/docs/drivers/csharp/current/serialization/poco.md#std-label-csharp-poco

  • [Customize Class Mapping](https://www.mongodb.com/docs/drivers/csharp/current/serialization/class-mapping.md#std-label-csharp-class-mapping

  • [Serialization](https://www.mongodb.com/docs/drivers/csharp/current/serialization.md#std-label-csharp-serialization

  • [Polymorphic Objects](https://www.mongodb.com/docs/drivers/csharp/current/serialization/polymorphic-objects.md#std-label-csharp-polymorphism

Find All Documents

An empty query filter matches all documents in a collection. The following example shows how to create an empty query filter:

var filter = Builders<Guitar>.Filter.Empty;

Comparison Operators

Comparison operators compare the query value to the value in a specified field. Some of these methods have alternative syntax that you can use in place of the method, as shown in the following example:

var filter = Builders<Guitar>.Filter.Eq(g => g.Make, "Fender");
var results = guitarCollection.Find(filter).ToList();

// Alternative syntax
var results = guitarCollection.Find(g => g.Make == "Fender").ToList();;

The following table lists the .NET/C# Driver methods for comparison operations and the equivalent MongoDB Server operators:

.NET/C# Driver Method Alternative Syntax Description MongoDB Server Operator
Eq() == Matches documents where the value of the specified field is equal to the query value. $eq
Gt() > Matches documents where the value of the specified field is greater than the query value. $gt
Gte() >= Matches documents where any element in the specified array field is greater than or equal to the query value. $gte
In() N/A Matches documents where any element in the specified array field matches any value in the query array. $in
Lt() < Matches documents where any element in the specified array field is less than the query value. $lt
Lte() <= Matches documents where any element in the specified array field is less than or equal to the query value. $lte
Ne() != Matches documents where any element in the specified array field is not equal to the query value. $ne
Nin() N/A Matches documents where one of the following is true: None of the elements in the specified array field matches any of the values in the query array.; The specified field doesn't exist. $nin
StringIn() N/A Matches documents where the string value of the specified field matches any string value in the query array. $in
StringNin() N/A Matches documents where the string value of the specified field doesn't match any of the string values in the query array. $in

The following example calls the Find() method and passes a lambda filter, which the driver translates to a query filter. The query matches all documents where the establishedYear field is greater than 1985.

// Finds all documents with an "establishedYear" value greater than 1985
var results = guitarCollection.Find(g => g.EstablishedYear > 1985).ToList();

foreach (var doc in results)
{
    // Prints the documents in bson (json) format
    Console.WriteLine(doc.ToBsonDocument());
}

Output:

{ "_id" : 4, "make" : "Kiesel", "models" : ["Ares", "Vader", "Solo"], "establishedYear" : 2015, "rating" : null }

The following example uses builders to create a query filter that matches the same documents as the preceding example:

// Creates a filter for all documents with an "establishedYear" value greater
// than 1985
var filter = Builders<Guitar>.Filter.Gt(g => g.EstablishedYear, 1985);

// Finds all documents that match the filter
var result = guitarCollection.Find(filter).ToList();

foreach (var doc in result)
{
    // Prints the documents in bson (json) format
    Console.WriteLine(doc.ToBsonDocument());
}

Output:

{ "_id" : 4, "make" : "Kiesel", "models" : ["Ares", "Vader", "Solo"], "establishedYear" : 2015, "rating" : null }

The following example calls the Find() method and passes a lambda expression, which the driver translates to a query filter. The query matches all documents where the make field equals “Fender”.

// Finds all documents with a "make" value of "Fender"
var results = guitarCollection.Find(g => g.Make == "Fender").ToList();

foreach (var doc in results)
{
    // Prints the documents in bson (json) format
    Console.WriteLine(doc.ToBsonDocument());
}

Output:

{ "_id" : 1, "make" : "Fender", "models" : ["Stratocaster", "Telecaster"], "establishedYear" : 1946, "rating" : 9 }

The following example uses builders to create a query filter that matches the same documents as the preceding example:

// Creates a filter for all documents with a "make" value of "Fender"
var filter = Builders<Guitar>.Filter.Eq(g => g.Make, "Fender");

// Finds all documents that match the filter
var result = guitarCollection.Find(filter).ToList();

foreach (var doc in result)
{
    // Prints the documents in bson (json) format
    Console.WriteLine(doc.ToBsonDocument());
}

Output:

{ "_id" : 1, "make" : "Fender", "models" : ["Stratocaster", "Telecaster"], "establishedYear" : 1946, "rating" : 9 }

Logical Operators

Logical operators combine two or more expressions and return results based on the results of those expressions. These methods have alternative syntax that you can use in place of the method, as shown in the following example:

var builder = Builders<Guitar>.Filter;
var filter = builder.And(
   builder.Gte(g => g.EstablishedYear, 1985),
   builder.Ne(r => r.Make, "Kiesel"));

var results = guitarCollection.Find(filter).ToList();

// Alternative syntax
var results = guitarCollection.Find(
   g => g.EstablishedYear >= 1985
   && g.Make != "Kiesel")
.ToList();

The following table lists the .NET/C# Driver methods for logical operations and the equivalent MongoDB Server operators:

.NET/C# Driver Method Alternative Syntax Description MongoDB Server Operator
And() && Matches documents where all expressions evaluate to true. $and
Or() || Matches documents where one or more expressions evaluates to true. $or
Not() N/A Matches documents where at least one of the following is true: The document does not match the specified expression.; The document does not contain the field specified in the expression. $not

The following example calls the Find() method and passes a lambda expression, which the driver translates to a query filter. The query matches all documents where the establishedYear field is greater than or equal to 1985, and the make field is not equal to “Kiesel”.

// Finds all documents with an "establishedYear" value greater than 1985
// and a "make" value that is not equal to "Kiesel"
var results = guitarCollection.Find(g => g.EstablishedYear >= 1985 && r.Make != "Kiesel").ToList();

foreach (var doc in results)
{
    // Prints the documents in bson (json) format
    Console.WriteLine(doc.ToBsonDocument());
}

Output:

{ "_id" : 3, "make" : "PRS", "models" : ["Silver Sky", "SE", "Custom"], "establishedYear" : 1985, "rating" : 9 }

The following example uses builders to create a query filter that matches the same documents as the preceding example:

// Creates a filter for all documents with an "establishedYear" value greater
// than 1985 and a "make" value that does not equal "Kiesel"
var builder = Builders<Guitar>.Filter;
var filter = builder.And(builder.Gte(g => g.EstablishedYear, 1985), builder.Ne(r => r.Make, "Kiesel"));

// Finds all documents that match the filter
var result = guitarCollection.Find(filter).ToList();

foreach (var doc in result)
{
    // Prints the documents in bson (json) format
    Console.WriteLine(doc.ToBsonDocument());
}

Output:

{ "_id" : 3, "make" : "PRS", "models" : ["Silver Sky", "SE", "Custom"], "establishedYear" : 1985, "rating" : 9 }

Array Operators

Array operators match documents based on the value or quantity of elements in an array field. The following table lists the .NET/C# Driver methods for array operations and the equivalent MongoDB Server operators:

.NET/C# Driver Method Description MongoDB Server Operator
All() Matches documents where the values in the specified array field match all query values. $all
AnyEq() Matches documents where any element in the specified array field matches the query value. $elemMatch
AnyGt() Matches documents where any element in the specified array field is greater than the query value. $elemMatch
AnyGte() Matches documents where any element in the specified array field is greater than or equal to the query value. $elemMatch
AnyIn() Matches documents where any element in the specified array field matches any value in the query array. $elemMatch
AnyLt() Matches documents where any element in the specified array field is less than the query value. $elemMatch
AnyLte() Matches documents where any element in the specified array field is less than or equal to the query value. $elemMatch
AnyNe() Matches documents where any element in the specified array field is not equal to the query value. $elemMatch
AnyNin() Matches documents where one of the following is true: Any element in the specified array field isn't in the query array.; The specified field doesn't exist. $elemMatch
AnyStringIn() Matches documents where any string element in the specified array field matches any string value in the query array. $elemMatch
AnyStringNin() Matches documents where one of the following is true: Any string element in the specified array field isn't in the query array.; The specified field doesn't exist. $elemMatch
ElemMatch() Matches documents where any element in the specified array field matches the query criteria. $elemMatch
Size() Matches documents where the specified array field is the specified size. $size
SizeGt() Matches documents where the specified array field is larger than the specified size. $size
SizeGte() Matches documents where the specified array field is larger than or equal to the specified size. $size
SizeLt() Matches documents where the specified array field is smaller than the specified size. $size
SizeLte() Matches documents where the specified array field is smaller than or equal to the specified size. $size

The following example uses builders to create a query filter that matches all documents that have exactly three elements in the models field:

// Creates a filter for all documents with 3 elements in the "models" field
var filter = Builders<Guitar>.Filter.Size(g => g.Models, 3);

// Finds all documents that match the filter
var result = guitarCollection.Find(filter).ToList();

foreach (var doc in result)
{
    // Prints the documents in bson (json) format
    Console.WriteLine(doc.ToBsonDocument());
}

Output:

{ "_id" : 2, "make" : "Gibson", "models" : ["Les Paul", "SG", "Explorer"], "establishedYear" : 1902, "rating" : 8 }
{ "_id" : 3, "make" : "PRS", "models" : ["Silver Sky", "SE", "Custom"], "establishedYear" : 1985, "rating" : 9 }
{ "_id" : 4, "make" : "Kiesel", "models" : ["Ares", "Vader", "Solo"], "establishedYear" : 2015, "rating" : null }

Element Operators

Element operators match document query data based on the presence or type of a field. The following table lists the .NET/C# Driver methods for element operations and the equivalent MongoDB Server operators:

.NET/C# Driver Method Description MongoDB Server Operator
Exists() Matches documents that contain or don't contain a specified field, including documents where the field value is null. $exists
Type() Matches documents where the value of the specified field is an instance of the specified BSON types. $type

The following example uses builders to create a query filter that matches all documents that have a rating field:

// Creates a filter for all documents with a populated "ratings" field
var filter = Builders<Guitar>.Filter.Exists(g => g.Rating);

// Finds all documents that match the filter
var result = guitarCollection.Find(filter).ToList();

foreach (var doc in result)
{
    // Prints the documents in bson (json) format
    Console.WriteLine(doc.ToBsonDocument());
}

Output:

{ "_id" : 1, "make" : "Fender", "models" : ["Stratocaster", "Telecaster"], "establishedYear" : 1946, "rating" : 9 }
{ "_id" : 2, "make" : "Gibson", "models" : ["Les Paul", "SG", "Explorer"], "establishedYear" : 1902, "rating" : 8 }
{ "_id" : 3, "make" : "PRS", "models" : ["Silver Sky", "SE", "Custom"], "establishedYear" : 1985, "rating" : 9 }
{ "_id" : 5, "make" : "Ibanez", "models" : ["RG", "AZ"], "establishedYear" : 1957, "rating" : 7 }

Evaluation Operators

Evaluation operators analyze data in individual fields or all documents in the collection. The following table lists the .NET/C# Driver methods for evaluation operations and the equivalent MongoDB Server operators:

.NET/C# Driver Method Description MongoDB Server Operator
JsonSchema() Matches documents that satisfy the specified JSON schema. $jsonSchema
Mod() Matches documents where the value of the specified field divided by a divisor has the specified remainder (modulo). $mod
RegEx() Matches documents where the value of the specified field matches a specified regular expression. $regex
Where() Use to pass either a string containing a JavaScript expression or a full JavaScript function to the query system. $where

The following example uses builders to create a query filter that matches all documents that have a value in the make field that starts with the letter “G”:

// Creates a filter for all documents with a populated "ratings" field
var filter = Builders<Guitar>.Filter.Regex(g => g.Make, "^G");

// Finds all documents that match the filter
var result = guitarCollection.Find(filter).ToList();

foreach (var doc in result)
{
    // Prints the documents in bson (json) format
    Console.WriteLine(doc.ToBsonDocument());
}

Output:

{ "_id" : 2, "make" : "Gibson", "models" : ["Les Paul", "SG", "Explorer"], "establishedYear" : 1902, "rating" : 8 }

Geospatial Operators

Geospatial operators return data based on geospatial expression conditions. The following table lists the .NET/C# Driver methods for geospatial operations and the equivalent MongoDB Server operators:

.NET/C# Driver Method Description MongoDB Server Operator
GeoIntersects() Matches documents whose geospatial data intersects with a specified GeoJsonObject. $geoIntersects
GeoWithin() Matches documents whose geospatial data is entirely within the specified shape. $geoWithin
GeoWithinBox() Matches documents whose geospatial data is entirely within the specified box. $geoWithin, $box
GeoWithinCenter() Matches documents whose geospatial data is entirely within the specified circle. $geoWithin, $center
GeoWithinCenterSphere() Matches documents whose geospatial data is entirely within the specified sphere. $geoWithin, $centerSphere
GeoWithinPolygon() Matches documents whose geospatial data is entirely within the specified polygon. $geoWithin, $polygon
Near() Specifies a point for which a geospatial query returns the documents from nearest to farthest. $near
NearSphere() Specifies a point for which a geospatial query returns the documents from nearest to farthest in spherical geometry. $nearSphere

Bitwise Operators

Bitwise operators matches documents based on bit-position conditions. The following table lists the .NET/C# Driver methods for bitwise operations and the equivalent MongoDB Server operators:

.NET/C# Driver Method Description MongoDB Server Operator
BitsAllClear() Matches documents where all the specified bit positions are clear (0) in the specified field. $bitsAllClear
BitsAllSet() Matches documents where all the specified bit positions are set (1) in the specified field. $bitsAllSet
BitsAnyClear() Matches documents where any of the specified bit positions are clear (0) in the specified field. $bitsAnyClear
BitsAnySet() Matches documents where any of the specified bit positions are set (1) in the specified field. $bitsAnySet

Other Operators

The .NET/C# Driver also provides the following methods that create filter definitions:

.NET/C# Driver Method Description
OfType() Matches documents of a type derived from the specified type. You can use overloads of this method to specify additional query criteria.
Text() Matches documents with a field that contains the specified string.

Additional Information

For more information about any of the driver methods on this page, see the API documentation for the FilterDefinitionBuilder\<TDocument> class.