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

Specify a Query

On this page

  • Overview
  • Literal Values
  • Comparison Operators
  • Logical Operators
  • Array Operators
  • Element Operators
  • Evaluation Operators
  • Additional Information

In this guide, you can learn how to specify a query using the MongoDB .NET/C# Driver.

You can narrow the set of matched documents returned by your query by creating a query filter. A query filter is an expression that specifies the documents you want to match in a read, update, or delete operation.

Note

Using LINQ

This guide shows how to specify queries using query filters. You can also specify queries using LINQ. To learn more about using LINQ, see LINQ.

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; }
}

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 about custom serialization, see Custom Serialization.

To learn more about class mapping, see Class Mapping.

The following code instantiates the _guitarsCollection object using the Guitar class as a type parameter. This type parameter causes the driver to automatically serialize and deserialize the documents it sends to and receives from MongoDB to instances of the Guitar class:

private static IMongoCollection<Guitar> _guitarsCollection;

Literal value queries return documents with an exact match to your query filter.

The following example specifies a query filter as a parameter to the Find() method. The query matches all documents where the make field equals "Fender".

// Finds all documents with a "make" value of "Fender"
var results = _guitarsCollection.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 = _guitarsCollection.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 }

Tip

Find All Documents

Use an empty query filter to match all documents in the collection. Create an empty query filter with builders as follows:

var result = _guitarsCollection.Find(Builders<Guitar>.Filter.Empty).ToList();

To learn more about using builders, see Operations with Builders.

Comparison operators analyze the value in a document against the specified value in your query filter. Common comparison operators include:

Operator
Builder
Description
>
Gt()
Greater than
<=
Lte()
Less than or equal to
!=
Ne()
Not equal to

For a full list of comparison operators, see the Comparison Query Operators page.

The following example specifies a query filter as a parameter to the Find() method. The query matches all documents where the establishedYear field is greater than 1985.

// Finds all documents with am "establishedYear" value greater than 1985
var results = _guitarsCollection.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 = _guitarsCollection.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 }

To learn more about using builders, see Operations with Builders.

Logical operators match documents using logic applied to the results of two or more sets of expressions. The following is a list of some logical operators:

Operator
Builder
Description
&&
And()
All expressions must evaluate to true.
||
Or()
At least one expression must evaluate to true.

For a full list of logical operators, see the Logical Query Operators page.

The following example specifies a query filter as a parameter to the Find() method. 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 = _guitarsCollection.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 = _guitarsCollection.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 }

To learn more about using builders, see Operations with Builders.

Array operators match documents based on the value or quantity of elements in an array field. The following is a list of builder methods that use array operators:

Operator
Description
All()
Matches documents if the array field contains all elements specified in the query.
Any()
Matches documents if any element in the array field matches the specified query filter.
Size()
Matches documents if the array field is a specified size.

Note

The Any() builder uses the $elemMatch query operator.

To learn more about the $elemMatch query selector, see $elemMatch.

For more information on the array operators, see the Array Query Operators page.

The following example uses builders to create a query filter that matches all documents that have 3 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 = _guitarsCollection.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 }

To learn more about using builders, see Operations with Builders.

Element operators query data based on the presence or type of a field.

For a full list of element operators, see the Element Query Operators page.

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 = _guitarsCollection.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 }

To learn more about using builders, see Operations with Builders.

Evaluation operators analyze data on individual fields, or on the entire collection's documents. Some builder methods that use evaluation operators include Regex() and Text().

For a full list of evaluation operators, see the Evaluation Query Operators page.

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 = _guitarsCollection.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 }

To learn more about using builders, see Operations with Builders.

For more information about the operators mentioned in this guide, see the following Server Manual Entries:

To learn more about using Builders, see Operations with Builders.

To learn how to specify queries using LINQ, see LINQ.

Back

BSON Operations