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.
Sample Data
The examples in this guide use the planets collection from the
sample_guides database. The documents in this collection use the
following Planet class as a model:
public class Planet { public ObjectId _id { get; set; } public string name { get; set; } public int orderFromSun { get; set; } public bool hasRings { get; set; } }
This collection is from the sample datasets provided by Atlas. See the Quick Start guide to learn how to create a free MongoDB cluster and load this sample data.
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); }
Query a Shadow Property
A shadow property is a property that isn't defined on your .NET entity class but is included in the Entity Framework model and mapped to fields in the database. You can use shadow properties to query or track data in your documents without exposing it as a property on your entity.
To reference a shadow property in a LINQ query, call the EF.Property<T>() method and
pass the configured property name as an argument. The generic type argument must match the
data type of the shadow property.
For example, the Planet class does not define a property for the mainAtmosphere
field. To configure this field as a shadow property, call the
Property<T>() method in the OnModelCreating() method of
PlanetDbContext, as shown in the following example:
public class PlanetDbContext : DbContext { public DbSet<Planet> Planets { get; init; } public static PlanetDbContext Create(IMongoDatabase database) => new(new DbContextOptionsBuilder<PlanetDbContext>() .UseMongoDB(database.Client, database.DatabaseNamespace.DatabaseName) .Options); public PlanetDbContext(DbContextOptions options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<Planet>().ToCollection("planets"); modelBuilder.Entity<Planet>().Property<string[]>("mainAtmosphere"); } }
The call to modelBuilder.Entity<Planet>().Property<string[]>("mainAtmosphere")
instructs the framework to include mainAtmosphere in the model
and map it to a string[] field in MongoDB.
The following code uses the EF.Property<string[]>() method to find all planets that
have a non-empty mainAtmosphere shadow property and prints the planet
names to the console:
var planets = db.Planets.Where( p => EF.Property<string[]>(p, "mainAtmosphere").Length > 0); foreach (var p in planets) { Console.WriteLine(p.name); }
Check Field Existence
You can query documents based on whether a field exists, is missing, or has a null
value by using methods in the Mql class.
Note
These methods work with both real properties and shadow properties.
Mql.Exists
The Mql.Exists() method matches documents that contain the specified field,
including documents where the field value is null.
The following code uses the Mql.Exists() method to find all planets that
have the hasRings field and prints the planet names to the console:
var planets = db.Planets.Where(p => Mql.Exists(p.hasRings)); foreach (var p in planets) { Console.WriteLine(p.name); }
Mql.IsMissing
The Mql.IsMissing() method matches documents that do not contain the
specified field.
The following code uses the Mql.IsMissing() method to find all planets that
do not have the hasRings field and prints the planet names to the console:
var planets = db.Planets.Where(p => Mql.IsMissing(p.hasRings)); foreach (var p in planets) { Console.WriteLine(p.name); }
Mql.IsNullOrMissing
The Mql.IsNullOrMissing() method matches documents where the specified
field is either missing or has a null value.
The following code uses the Mql.IsNullOrMissing() method to find all planets
where the hasRings field is missing or null and prints the planet
names to the console:
var planets = db.Planets.Where(p => Mql.IsNullOrMissing(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 alongor the number of documents that match a predicateAny(): Returnstrueif 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:
To learn more about the Mql class methods, see the following .NET/C# Driver
API documentation links: