Docs Menu
Docs Home
/ / /
C#/.NET
/ /

Create a Query Filter

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.

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

  • Class Mapping

  • Serialization

  • Polymorphic Objects

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 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.

Gt()

>

Matches documents where the value of the specified field is greater than the query value.

Gte()

>=

Matches documents where any element in the specified array field is greater than or equal to the query value.

In()

N/A

Matches documents where any element in the specified array field matches any value in the query array.

Lt()

<

Matches documents where any element in the specified array field is less than the query value.

Lte()

<=

Matches documents where any element in the specified array field is less than or equal to the query value.

Ne()

!=

Matches documents where any element in the specified array field is not equal to the query value.

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.

StringIn()

N/A

Matches documents where the string value of the specified field matches any string value in the query array.

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.

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());
}
{ "_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());
}
{ "_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());
}
{ "_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());
}
{ "_id" : 1, "make" : "Fender", "models" : ["Stratocaster", "Telecaster"], "establishedYear" : 1946, "rating" : 9 }

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.

Or()

||

Matches documents where one or more expressions evaluates to true.

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());
}
{ "_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());
}
{ "_id" : 3, "make" : "PRS", "models" : ["Silver Sky", "SE", "Custom"], "establishedYear" : 1985, "rating" : 9 }

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.

AnyEq()

Matches documents where any element in the specified array field matches the query value.

AnyGt()

Matches documents where any element in the specified array field is greater than the query value.

AnyGte()

Matches documents where any element in the specified array field is greater than or equal to the query value.

AnyIn()

Matches documents where any element in the specified array field matches any value in the query array.

AnyLt()

Matches documents where any element in the specified array field is less than the query value.

AnyLte()

Matches documents where any element in the specified array field is less than or equal to the query value.

AnyNe()

Matches documents where any element in the specified array field is not equal to the query value.

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.

AnyStringIn()

Matches documents where any string element in the specified array field matches any string value in the query array.

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()

Matches documents where any element in the specified array field matches the query criteria.

Size()

Matches documents where the specified array field is the specified size.

SizeGt()

Matches documents where the specified array field is larger than the specified size.

SizeGte()

Matches documents where the specified array field is larger than or equal to the specified size.

SizeLt()

Matches documents where the specified array field is smaller than the specified size.

SizeLte()

Matches documents where the specified array field is smaller than or equal to the specified 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());
}
{ "_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 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.

Type()

Matches documents where the value of the specified field is an instance of the specified BSON types.

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());
}
{ "_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 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.

Mod()

Matches documents where the value of the specified field divided by a divisor has the specified remainder (modulo).

RegEx()

Matches documents where the value of the specified field matches a specified regular expression.

Where()

Use to pass either a string containing a JavaScript expression or a full JavaScript function to the query system.

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());
}
{ "_id" : 2, "make" : "Gibson", "models" : ["Les Paul", "SG", "Explorer"], "establishedYear" : 1902, "rating" : 8 }

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.

GeoWithin()

Matches documents whose geospatial data is entirely within the specified shape.

GeoWithinBox()

Matches documents whose geospatial data is entirely within the specified box.

GeoWithinCenter()

Matches documents whose geospatial data is entirely within the specified circle.

GeoWithinCenterSphere()

Matches documents whose geospatial data is entirely within the specified sphere.

GeoWithinPolygon()

Matches documents whose geospatial data is entirely within the specified polygon.

Near()

Specifies a point for which a geospatial query returns the documents from nearest to farthest.

NearSphere()

Specifies a point for which a geospatial query returns the documents from nearest to farthest in spherical geometry.

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 of the specified bit positions are clear (0) in the specified field.

BitsAllSet()

Matches documents where all of the specified bit positions are set (1) in the specified field.

BitsAnyClear()

Matches documents where any of the specified bit positions are clear (0) in the specified field.

BitsAnySet()

Matches documents where any of the specified bit positions are set (1) in the specified field.

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.

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

Back

Query Documents

On this page

  • Overview
  • Find All Documents
  • Comparison Operators
  • Logical Operators
  • Array Operators
  • Element Operators
  • Evaluation Operators
  • Geospatial Operators
  • Bitwise Operators
  • Other Operators
  • Additional Information