Query Data
Overview
Entity Framework Core allows you to work with data in your application without explicitly running database commands. To query your data, use the Language-Integrated Query (LINQ) syntax. LINQ allows you to write strongly typed queries using C#-specific keywords and operators. When you run the application, the EF Core Provider automatically translates the LINQ queries and runs them on the database using the MongoDB Query API.
In this guide you can see examples of common query operations on an application configured to use the EF Core Provider.
Tip
To learn how to configure an application to use the EF Core Provider, see Configure the EF Core Provider.
Find Entities
Find a single entity by using the FirstOrDefault()
method, or find
multiple entities by using the Where()
method.
Find a Single Entity
The FirstOrDefault()
method returns the first entity it finds in your collection that
matches the search criteria, and returns null
if no matching entities
are found.
The following code uses the FirstOrDefault()
method to find a planet with
the name
field of "Mercury" from a DBSet
called Planets
and prints
the planet name to the console:
var planet = db.Planets.FirstOrDefault(p => p.name == "Mercury"); Console.WriteLine(planet.name);
Find Multiple Entities
You can use the Where()
method to retrieve multiple entities from your
collections. Where()
returns all entities that match the search
criteria.
The following code uses the Where()
method to find all planets that have the
hasRings
field set to true
and prints the planet names to the console.
var planets = db.Planets.Where(p => p.hasRings); foreach (var p in planets) { Console.WriteLine(p.name); }
Sort Entities
Use the OrderBy()
method to specify an order in which to return entities
from a query. OrderBy()
sorts the elements in ascending order based on a
specified sort criteria.
The following code uses the OrderBy()
method to find all planets and sort
them by the value of the orderFromSun
field in ascending order. It then
prints the results to the console.
var planetList = db.Planets.OrderBy(p => p.orderFromSun); foreach (var p in planetList) { Console.WriteLine(p.name); }
Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune
Tip
Sort in Descending Order
You can sort the results of a query in descending order by using the
OrderByDescending()
method.
You can perform a secondary sort on your query by using the ThenBy()
method. The
ThenBy()
method sorts the results of the OrderBy()
method in ascending
order based on a specified sort criteria. The ThenBy()
method should be
chained to the OrderBy()
method.
Tip
Secondary Sort in Descending Order
You can perform a secondary sort in descending order by using the
ThenByDescending()
method.
The following code uses the OrderBy()
and ThenBy()
methods to find all
planets and sort them by the hasRings()
field, with a secondary sort
on the name
field.
var planetList = db.Planets.OrderBy(o => o.hasRings).ThenBy(o => o.name); foreach (var p in planetList) { Console.WriteLine("Has rings: " + p.hasRings + ", Name: " + p.name); }
Has rings: False, Name: Earth Has rings: False, Name: Mars Has rings: False, Name: Mercury Has rings: False, Name: Venus Has rings: True, Name: Jupiter Has rings: True, Name: Neptune Has rings: True, Name: Saturn Has rings: True, Name: Uranus
Tip
When sorting on fields with a boolean value, entities with a field value of
false
show before those with a value of true
.
Scalar Aggregations
The EF Core Provider supports the following scalar aggregation methods:
Count()
: Returns the number of elements in a collection or the number of documents that match a predicateLongCount()
: Returns the number of elements in a collection as along
or the number of documents that match a predicateAny()
: Returnstrue
if any elements in a collection match the predicateMax()
: Returns the maximum value of a specified field in a collectionMin()
: Returns the minimum value of a specified field in a collectionSum()
: Returns the sum of values of a specified field in a collectionAverage()
: Returns the average of values of a specified field in a collection
The following sections show examples of each of the preceding methods.
Count
The following example uses the Count()
method to count the number of elements in the
Planets
collection:
var planetCount = db.Planets.Count(); Console.WriteLine("Planet Count: " + planetCount);
The following example uses the Count()
method to count the number of elements in the
Planets
collection that have a hasRings
field set to true
:
var planetCountWithRings = db.Planets.Count(p => p.hasRings); Console.WriteLine("Planet Count with Rings: " + planetCountWithRings);
LongCount
The following example uses the LongCount()
method to count the number of
elements in the Planets
collection and returns the result as a long
:
var planetCountLong = db.Planets.LongCount(); Console.WriteLine("Long Planet Count: " + longCount);
The following example uses the LongCount()
method to count the number of
elements in the Planets
collection that have a hasRings
field set to
true
and returns the result as a long
:
var planetCountLongWithRings = db.Planets.LongCount(p => p.hasRings); Console.WriteLine("Long Planet Count with Rings: " + planetCountLongWithRings);
Any
The following example uses the Any()
method to check if any elements in the
Planets
collection have a hasRings
field set to true
:
var results = db.Planets.Any(p => p.hasRings); foreach (var p in results) { Console.WriteLine("Planet with Rings: " + p.name); }
Max
The following example uses the Max()
method to find the maximum value of the
orderFromSun
field in the Planets
collection:
var furthestPlanet = db.Planets.Max(p => p.orderFromSun); Console.WriteLine("Furthest Planet: " + furthestPlanet.name);
Min
The following example uses the Min()
method to find the minimum value of the
orderFromSun
field in the Planets
collection:
var closestPlanet = db.Planets.Min(p => p.OrderFromSun); Console.WriteLine("Closest Planet: " + closestPlanet.Name);
Sum
The following example uses the Sum()
method to find the sum of the
mass
field in the Planets
collection:
var totalMass = db.Planets.Sum(p => p.mass); Console.WriteLine("Total Mass of Planets: " + totalMass);
Average
The following example uses the Average()
method to find the average value of
the mass
field in the Planets
collection:
var averageMass = db.Planets.Average(p => p.mass); Console.WriteLine("Average Mass of Planets: " + averageMass);
Additional Information
To learn more about aggregations in MongoDB, see the Aggregation Operations guide in the MongoDB Server manual.
To learn more about the methods discussed in this guide, see the following .NET API documentation links: