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
  • Sample Class
  • Construct a Filter

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

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 }

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 }

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 }

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 }

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 }

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

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

The code examples in this guide demonstrate how you can use builders to create types to interact with documents in the sample collection plants.flowers. Documents in this collection are modeled by the following Flower class:

public class Flower
{
public ObjectId Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public double Price { get; set; }
public List<string> Season { get; set; }
public double Stock { get; set; }
public string Description { get; set; }
}

Each builder class takes a generic type parameter TDocument which represents the type of document that you are working with. In this guide, the Flower class is the document type used in each builder class example.

The FilterDefinitionBuilder class provides a type-safe interface for building up queries. Suppose you want to query your collection for documents matching the following criteria:

  • Price field value less than 20

  • Category field value is "Perennial"

Use builders to create the filter definition with the typed variant:

var builder = Builders<Flower>.Filter;
var filter = builder.Lt(f => f.Price, 20) & builder.Eq(f => f.Category, "Perennial");

Using the typed variant form provides compile-time safety. Additionally, your IDE can provide refactoring support.

Alternatively, you can use string-based field names to contruct the filter:

var builder = Builders<Flower>.Filter;
var filter = builder.Lt("Price", 20) & builder.Eq("Category", "Perennial");

If you are using LINQ, you can also use the Inject() method to apply the filter to a LINQ query:

var builder = Builders<Flower>.Filter;
var filter = builder.Lt("Price", 20) & builder.Eq("Category", "Perennial");
var query = collection.AsQueryable().Where(f => filter.Inject());

If your document has properties or fields that serialize to arrays, you can use the methods beginning with Any, such as AnyEq() or AnyLt(), to compare the entire array against a single item.

Use builders to check which documents in the collection have a Season array that includes "winter":

var builder = Builders<Flower>.Filter;
var filter = builder.AnyEq(f => f.Season, "winter");

You can also call the ElemMatch() method to find documents that have an array field that contains at least one element that matches a specified search criteria. The following example returns documents that contain the value "Summer" in their Season array:

var builder = Builders<Flower>.Filter;
var filter = builder.ElemMatch(f => f.Season, s => s == "Summer");

To learn more about array operators, see the Array Query Operators guide in the MongoDB Server manual.

Back

Query Documents