CRUD Operations in Mongodb Using .Net 10

MongoDB is one of the most popular NoSQL databases, known for its flexibility, scalability, and document-oriented data model. Unlike traditional relational databases that store data in tables and rows, MongoDB stores data as BSON documents, making it an excellent choice for modern applications that require agility and high performance.

With the release of .NET 10, developers can build faster and more efficient applications while leveraging the powerful MongoDB .NET Driver to interact with MongoDB databases. In this article, we'll explore how to perform CRUD (Create, Read, Update, and Delete) operations in MongoDB using .NET 10 through practical examples.

By the end of this tutorial, you'll be able to:
  • Connect a .NET 10 application to MongoDB.
  • Insert documents into a collection.
  • Retrieve documents using various query techniques.
  • Update existing documents.
  • Delete documents from a collection.
  • Follow best practices for MongoDB development in .NET.

Before proceeding with CRUD operations, it is recommended to have a basic understanding of MongoDB concepts such as databases, collections, and document structure.

In my previous article, I covered the fundamentals of MongoDB, including:
  • What MongoDB is and how it differs from traditional relational databases.
  • Installing and configuring MongoDB.
  • Creating and selecting databases.
  • Creating and managing collections.
  • Listing available databases and collections.
  • Dropping databases and collections.
  • Understanding MongoDB's document-based architecture.

If you're new to MongoDB, I recommend reading that article first, as it provides the foundation required for working with MongoDB in .NET applications.

With those basics covered, this article focuses on performing CRUD (Create, Read, Update, and Delete) operations using the MongoDB .NET Driver in .NET 10 applications.

Demonstration: CRUD Operations in MongoDB

In this demonstration, we will build a simple Product Management Application(Console Application) using .NET 10 and MongoDB. The application will perform all four CRUD (Create, Read, Update, Delete) operations on a Product collection stored in MongoDB.

The Product model represents items available in an inventory or catalog. Each product contains the following information:
  • Id – A unique identifier generated by MongoDB.
  • Name – The name of the product.
  • Price – The cost of the product.
  • Category – The category to which the product belongs.
  • CreatedAt – The date and time when the product was created.

Throughout this demonstration, we will perform the following operations:

Create a Product

We will insert a new product document into the MongoDB collection. When a new product is created, MongoDB automatically generates a unique ObjectId that serves as the document's primary key.

Example:

{
  "name": "Laptop",
  "price": 75000,
  "category": "Electronics"
}

Read Products

We will retrieve product information from MongoDB. This includes:
  • Fetching all products from the collection.
  • Retrieving a specific product using its unique Id.
This operation demonstrates how data can be queried and returned to clients through the API.

Update a Product

We will modify the details of an existing product, such as changing its price or category. MongoDB will locate the document using its Id and update only the specified fields.

Example:

{
	"name": "Laptop", 
    "price": 70000, "
    category": "Electronics" 
}

Delete a Product

Finally, we will remove a product from the collection using its Id. Once deleted, the document will no longer be available in MongoDB.

By completing these operations, you will gain a practical understanding of how the MongoDB .NET Driver interacts with MongoDB collections and how CRUD functionality is implemented in a modern .NET 10 application.

Prerequisites

Before getting started, ensure you have the following installed:
  • .NET 10 SDK
  • MongoDB Server (local or cloud instance)
  • Visual Studio 2025 or Visual Studio Code
  • MongoDB .NET Driver package

Creating the Product Model (Mongodb Model)

Before performing CRUD operations, we need to define a model that represents the structure of the documents stored in MongoDB. In .NET, models are typically created as C# classes, where each property corresponds to a field in the MongoDB document.

MongoDB stores data in BSON (Binary JSON) format. The MongoDB .NET Driver provides attributes that allow us to map C# properties to BSON document fields.


using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
public class Product
{
  [BsonId]
  [BsonRepresentation(BsonType.ObjectId)]
public string? Id { get; set; }

[BsonElement("name")]
public string Name { get; set; } = string.Empty;

[BsonElement("price")]
public decimal Price { get; set; }

[BsonElement("category")]
public string Category { get; set; } = string.Empty;

[BsonElement("createdAt")]
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
}

Understanding the Attributes

  • [BsonId]: marks the property as the primary identifier of the document.
  • [BsonRepresentation(BsonType.ObjectId)]: allows MongoDB's ObjectId value to be represented as a C# string.
  • [BsonElement("fieldName")]: maps a C# property to a specific field name in the MongoDB document.

When a Product object is stored in MongoDB, it will look similar to the above document mentioned in the Create a Product section.

This model serves as the foundation for all MongoDB CRUD operations. The MongoDB driver automatically handles the conversion between C# objects and MongoDB documents, making it easy to insert, retrieve, update, and delete data.

Configuring MongoDB Connection

Before performing CRUD operations, the application must establish a connection to the MongoDB server. The MongoDB .NET Driver provides the MongoClient class, which is responsible for connecting to a MongoDB instance and interacting with databases and collections.

In this demonstration, we will connect to a local MongoDB server running on the default port (27017) and access a database named ProductDb.

Creating the MongoDB Connection

Create a MongoDB client and access the database:

using MongoDB.Driver;

var connectionString = "mongodb://localhost:27017";

var client = new MongoClient(connectionString);

var database = client.GetDatabase("ProductDb");

var productsCollection = database.GetCollection<Product>("Products");

Understanding the Code

  • MongoClient: establishes a connection to the MongoDB server.
  • GetDatabase(): retrieves a reference to the specified database. If the database does not exist, MongoDB creates it automatically when data is inserted.
  • GetCollection<Product>(): retrieves a collection named Products and maps its documents to the Product model.
  • The generic type parameter (Product) enables automatic serialization and deserialization between C# objects and MongoDB documents.

If you are using MongoDB Atlas instead of a local MongoDB instance, replace the connection string with your Atlas connection string:



var connectionString = "mongodb+srv://<username>:<password>@cluster0.xxxxx.mongodb.net/";


For security reasons, avoid hardcoding credentials in production applications. Store connection strings in configuration files, environment variables, or a secure secrets management solution.

After establishing the connection, the application is ready to perform Create, Read, Update, and Delete operations on the Products collection.

Implementing MongoDB CRUD Operations

With the MongoDB connection configured and the Product model in place, we can now implement the core CRUD operations. In this demonstration, all operations will be executed against the Products collection in MongoDB using the MongoDB .NET Driver.

Create Operation

The Create operation is used to add a new document to the collection. When a new Product object is inserted, MongoDB automatically generates a unique _id value if one is not provided.
This operation is useful when adding new products to the inventory or catalog.
Purpose: Insert a new product document into the database.

Implementing the Create Operation

Insert a new Document

var product = new Product
{
  Name = "Laptop",
  Price = 999.99m,
  Stock = 20
  };
  await products.InsertOneAsync(product);
  Console.WriteLine("Product inserted successfully.");

This code creates a new product and inserts it into the MongoDB collection asynchronously. It uses InsertOneAsync to store the document and confirms insertion in the console.


Insert Multiple Documents

var items = new List<Product>
{
    new() { Name = "Mouse", Price = 25, Stock = 100 },
    new() { Name = "Keyboard", Price = 50, Stock = 75 }
};

await products.InsertManyAsync(items);

This code creates a products collection and inserts it into the MongoDB collection asynchronously. It uses InsertManyAsync to store the document and confirms insertion in the console.


Read Operation

The Read operation retrieves data from the collection. Depending on the requirement, it can be used to fetch:

  • All products in the collection.
  • A specific product by its unique identifier.
  • Products that match certain criteria or filters.

This operation allows users to view and search product information stored in MongoDB.
Purpose: Retrieve one or more product documents from the database.

Implementing the Read Operation

Get All Documents

var allProducts =
await products.Find(_ => true).ToListAsync();
foreach(var item in allProducts)
{
  Console.WriteLine(item.Name);
}

This code is used to retrieve all products from MongoDB and display their names in the console. It uses products.Find(_ => true) return all documents from the collection (no filter applied).


Find a Specific Product


var laptop = await products.Find(x => x.Name == "Laptop").FirstOrDefaultAsync();

This code is used to find a single product (Laptop) from MongoDB based on its name. It retrieves the first matching record using the FirstOrDefaultAsync method. If multiple products have the name "Laptop", only the first matching record is returned.


Filtering Records


var expensiveProducts = await products.Find(x => x.Price > 500).ToListAsync();

Searches the Products collection by applying a filter to return products with a price greater than 500. It returns all matching products as a list.

Update Operation

The Update operation modifies an existing document. MongoDB locates the target document using a filter, typically the product's Id, and updates the specified fields.

For example, a product's price, name, or category can be changed without replacing the entire document.

Purpose: Update existing product information in the database.

Implementing the Update Operation

Update a Single Document

var update = Builders<Product>.Update.Set(x => x.Price, 1099.99m);

await products.UpdateOneAsync(x => x.Name == "Laptop",update);

Update Multiple Documents

var updateStock = Builders<Product>.Update.Inc(x => x.Stock, 10);

await products.UpdateManyAsync(x => x.Stock < 50,updateStock);


Delete Operation

The Delete operation permanently removes a document from the collection. The document is typically identified by its unique Id before deletion.

This operation is useful when a product is discontinued or no longer needs to be stored in the database.

Purpose: Remove a product document from the database.

Implementing the Delete Operation

Delete One Document

await products.DeleteOneAsync(x => x.Name == "Laptop");


Delete Multiple Documents

await products.DeleteOneAsync(x => x.Stock == 0);


The sequence of operations in this demonstration is as follows:
  1. Create a new product and save it to MongoDB.
  2. Read the product data from the collection.
  3. Update one or more product properties.
  4. Delete the product from the collection.

By implementing these operations, you will learn how the MongoDB .NET Driver enables seamless interaction between C# objects and MongoDB documents, making data management straightforward in a .NET 10 application.

Best Practices

  • Use asynchronous APIs whenever possible.
  • Create indexes for frequently queried fields.
  • Store connection strings in configuration files or secrets.
  • Use dependency injection in ASP.NET Core applications.
  • Implement logging and exception handling.
  • Avoid loading large datasets into memory unnecessarily.

Summary

CRUD operations form the foundation of every data-driven application. Using MongoDB with .NET 10 is straightforward thanks to the official MongoDB .NET Driver. By understanding how to create, read, update, and delete documents efficiently, you can build scalable and high-performance applications that take full advantage of MongoDB's document database architecture.

Whether you're developing a small API or a large enterprise solution, mastering these CRUD operations is the first step toward effective MongoDB development in .NET.

Thanks

Kailash Chandra Behera

I am an IT professional with over 13 years of experience in the full software development life cycle for Windows, services, and web-based applications using Microsoft .NET technologies.

Previous Post Next Post

نموذج الاتصال