BrandGhost
MongoDB in C#: Simplified Guide For Inserting Data

MongoDB in C#: Simplified Guide For Inserting Data

03/22/2024(Updated 10/10/2026)

Most of the time when I'm developing applications, I default to using some form of SQL. Whether it's a simple application using SQlite or something a bit more robust that I plan to scale out with MySQL, it's inevitably some flavor of SQL. However, when starting new projects over the past few years I've been trying to make sure I have experience with document databases and have spent more time using MongoDB in C#.

In this article, I'll guide you through some basics for being able to insert data using MongoDB in C#. We'll keep it light and to the point, so let's dive into a brief overview of MongoDB in C# followed by some code examples in C#!

Remember to check out these platforms:


Overview of MongoDB in C#

MongoDB is a widely used NoSQL database that provides a flexible and scalable solution for data storage. One of the key benefits of MongoDB is its document-oriented nature so instead of using tables with fixed schemas like in traditional relational databases, MongoDB stores data in collections of JSON-like documents. This can allow for a more flexible and dynamic data model, especially in scenarios where data structures can vary.

In C#, you can seamlessly integrate MongoDB into your applications because MongoDB provides a native driver for C#. This simplifies the process of interacting with the database and provides a comfortable development experience for C# developers.

Well, mostly. If you're used to using SQL connections, SQL command objects, and DataReader classes to access your data, it's a little bit more cumbersome. But this is coming from the perspective of someone who prefers to write raw SQL queries in their data access layer. I suspect if you didn't have this bias then working with their API, especially for filtering, would feel pretty intuitive.

One big thing you'll want to keep in mind if you're coming from a relational database background is how you model related data. Normalization organizes relational data across related tables to reduce redundancy. In MongoDB, you can embed related data or reference documents in separate collections, depending on how the application reads and updates it. Embedding can avoid joins for data read together, but MongoDB also supports joins through the aggregation $lookup stage.

Follow Along with MongoDB in C# Content

I always try to make sure I provide multiple modes of content when I'm able to. Below you'll find a YouTube video walking through examples of MongoDB in C# for inserting records:

Of course, if you'd rather play around with some working code (aside from ensuring you have your own database), you can find the example code on my Dev Leader GitHub repository here. You should be able to clone it, set up your connection string properly, change your database and collection names as needed, and then rock and roll! The linked project targets net8.0 and references MongoDB.Driver 2.24.0; treat those as its historical dependency baseline, not a claim of compatibility with every newer driver.


Inserting Documents into MongoDB in C#

In this section, I'll explain how to insert documents into MongoDB using C#. We'll look at code examples using the InsertOne and InsertMany methods. We'll see these methods in their synchronous and asynchronous forms! Remember, you will need to ensure you have the "MongoDB.Driver" NuGet package installed in your project for the following code examples to work.

Using the InsertOne and InsertOneAsync Methods

To insert a single document into a MongoDB collection synchronously, use the InsertOne method. This method is straightforward and is executed immediately, blocking the current thread until the operation completes. Here's a basic example:

using MongoDB.Bson;
using MongoDB.Driver;

// Connect to MongoDB instance
var client = new MongoClient("mongodb://localhost:27017");

// Select database
var database = client.GetDatabase("testDatabase");

// Select collection (sort of like a SQL "table")
var collection = database.GetCollection<BsonDocument>("myCollection");

var document = new BsonDocument
{
    { "name", "John" },
    { "age", 30 }
};

// Insert document into collection
collection.InsertOne(document);

In this example:

  • We first establish a connection to the MongoDB instance and select our database and collection.
  • Then, we create a BsonDocument object, which represents the document we want to insert.
  • Finally, we call InsertOne on our collection object, passing in the document. This inserts the document into the specified collection.

For asynchronous operations, you can use InsertOneAsync. This method is especially useful in applications that require non-blocking operations, such as web applications or services, to maintain responsiveness. Here’s how to use it:

using MongoDB.Bson;
using MongoDB.Driver;
using System.Threading.Tasks;

// just like the former example
var client = new MongoClient("mongodb://localhost:27017");
var database = client.GetDatabase("testDatabase");
var collection = database.GetCollection<BsonDocument>("myCollection");

var document = new BsonDocument
{
    { "name", "Jane" },
    { "age", 28 }
};

// Asynchronously insert document
await collection.InsertOneAsync(document, cancellationToken: CancellationToken.None);

In this asynchronous example:

  • The setup is similar to the synchronous version, but we use await with InsertOneAsync. If the operation is incomplete, await suspends this method without blocking its thread and returns control to its caller. The next statement in this method still waits for the insert to complete; this alone does not start concurrent inserts.
  • Take note that you can pass in a cancellation token here which is a best practice for async code

Note that both InsertOne and InsertOneAsync methods throw exceptions if the insert operation fails, so you should use try-catch blocks to handle potential errors gracefully.

Using the InsertMany and InsertManyAsync Methods

The InsertMany method synchronously inserts a list of document objects into the specified collection. This is useful when you have multiple documents ready to be stored and want to execute the operation in a single call. Here's an example:

using MongoDB.Bson;
using MongoDB.Driver;
using System.Threading.Tasks;

// just like the former example
var client = new MongoClient("mongodb://localhost:27017");
var database = client.GetDatabase("testDatabase");
var collection = database.GetCollection<BsonDocument>("myCollection");

var documents = new List<BsonDocument>
{
    new BsonDocument("name", "John").Add("age", 30),
    new BsonDocument("name", "Jane").Add("age", 25),
    new BsonDocument("name", "Doe").Add("age", 28)
};

collection.InsertMany(documents);

In this example, we first get a reference to our collection. Then, we create a list of BsonDocument objects, each representing a document to insert. Finally, we call InsertMany with our list of documents. One method call is not an all-or-nothing transaction: by default, ordered insertion stops at the first error, while earlier successful inserts remain. With new InsertManyOptions { IsOrdered = false }, processing continues for other documents despite individual errors. See the official ordered and unordered insertion examples for partial-failure behavior.

For asynchronous operations, particularly useful in applications where responsiveness is crucial or when dealing with I/O-bound tasks, you can use the InsertManyAsync method. This method works similarly to InsertMany, but it performs the operation asynchronously. Here's an example:

using MongoDB.Bson;
using MongoDB.Driver;
using System.Threading.Tasks;

// just like the former example
var client = new MongoClient("mongodb://localhost:27017");
var database = client.GetDatabase("testDatabase");
var collection = database.GetCollection<BsonDocument>("myCollection");

var documents = new List<BsonDocument>
{
    new BsonDocument("name", "John").Add("age", 30),
    new BsonDocument("name", "Jane").Add("age", 25),
    new BsonDocument("name", "Doe").Add("age", 28)
};

await collection.InsertManyAsync(documents);

In this asynchronous version, await waits for InsertManyAsync to complete before this method continues, without blocking the calling thread while awaiting an incomplete operation. The same ordered/unordered partial-failure behavior applies; asynchronous execution does not make the batch transactional.


Best Practices for Efficiently Inserting Data

This article is focused on the API usage of inserting data into MongoDB using C#, but I wanted to touch on a few other points. To improve the efficiency of data insertion in MongoDB, you can consider the following best practices:

  1. Batch Inserts: Instead of inserting one document at a time, you can batch multiple documents together and insert them in a single operation using InsertMany. This reduces the overhead of multiple round-trips to the database.
  2. Choose Indexes for Your Workload: Indexes can speed up reads, but each index adds write-maintenance overhead because inserted documents also need index entries. Keep indexes that support your queries rather than adding them as a generic insertion optimization. See MongoDB's write-performance guidance.
  3. Consider Sharding: If you have a large amount of data to insert, sharding can distribute the data across multiple servers, improving insertion performance.
  4. The effective acknowledgment and durability requirements depend on your client settings and deployment defaults, not a universal Acknowledged default. Check the effective write concern for your deployment, including topology-dependent defaults. Choose it for your durability requirements; reducing acknowledgment can sacrifice guarantees.
  5. Consider Asynchronous Operations: Async APIs allow non-blocking waits and can help application responsiveness. Concurrent inserts require deliberately starting independent operations before awaiting their completion; sequentially awaiting each insert does not make them concurrent.

Aside from asynchronous versions of these APIs which were mentioned earlier, I won't be covering these other topics in more detail in this article. Stay tuned for upcoming articles where I cover these topics along with other functionality, such as updating documents in MongoDB and deleting records! We'll also need to know how we can filter records in C# for MongoDB to make all of those work!


Wrapping Up MongoDB in C#

To recap, in this article, we explored the topic of writing data to MongoDB in C# using InsertOne and InsertMany APIs. We saw both the synchronous and asynchronous versions of these APIs in functional code examples.

Some of the key takeaways:

  • Understanding relational database vs document database characteristics
  • Best practice considerations for performance
  • Synchronous vs asynchronous APIs for inserting data to MongoDB in C#
  • You should continuously improve your skills and stay updated with the latest technologies!

If you found this useful and you're looking for more learning opportunities, consider subscribing to my free weekly software engineering newsletter and check out my free videos on YouTube! Meet other like-minded software engineers and join my Discord community!

Affiliations

These are products & services that I trust, use, and love. I get a kickback if you decide to use my links. There’s no pressure, but I only promote things that I like to use!

  • BrandGhost: My social media content and scheduling tool that I use for ALL of my content!
  • RackNerd: Cheap VPS hosting options that I love for low-resource usage!
  • Contabo: Affordable VPS hosting options!
  • ConvertKit: The platform I use for my newsletter!
  • SparkLoop: Helps add value to my newsletter!
  • Opus Clip: Tool for creating short-form videos!
  • Newegg: For all sorts of computer components!
  • Bulk Supplements: Huge selection of health supplements!
  • Quora: I answer questions when folks request them!

Frequently Asked Questions: MongoDB in C#

What is MongoDB and how can I use MongoDB in C#?

MongoDB is a NoSQL database that can be used with C# to store and manage data. It provides a flexible schema, scalable performance, and high availability. In C#, MongoDB can be accessed using a driver that provides an easy-to-use API for interacting with the database.

What are the benefits of using MongoDB for data storage?

MongoDB offers several benefits for data storage, including horizontal scalability, automatic sharding, and flexible document structure. It allows for faster development cycles, as data can be stored in its natural form without the need for complex mappings or migrations. Additionally, MongoDB provides support for indexing, replication, and load balancing, ensuring high availability and performance of the database.

How can I efficiently insert documents into MongoDB in C#?

To efficiently insert documents into MongoDB using C#, you can utilize methods like 'InsertOne' and 'InsertMany'. These methods allow you to insert single or multiple documents respectively. It is recommended to batch inserts to reduce network overhead. Appropriate indexes support reads but add maintenance overhead to inserts, so select them for the query workload. It's important to optimize the insertion process based on the specific requirements of your application.

How To Update MongoDB Documents in C# - What You Need To Know

See code examples for how to update MongoDB documents in C#. This article covers the basics of different methods you can use to update records.

MongoDB Filtering in C# - Beginner's Guide For Easy Filters

Learn the basics of MongoDB Filtering in C# with simple code examples! See how to use the MongoDB FilterDefinitionBuilder to support filtering in MongoDB.

C# MongoDB Insert Benchmarks - What You Need To Know

Curious about C# MongoDB insert benchmarks? In this article, I show you BenchmarkDotNet code and the results for several variations of inserting data!

An error has occurred. This application may no longer respond until reloaded. Reload