MongoDB in C#: Simplified Guide For Inserting Data

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#!


What’s In This Article: MongoDB 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 understanding the primary differences between relational and document databases. In the former, we generally denormalize data across tables and, in the latter, we write the data as a document that we’d like to read back without having to join. These types of databases aren’t designed to join data like we do with relational databases, so it’s something to be aware of!

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:

YouTube player

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!


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. This tells the program to continue with other work that doesn’t depend on the completion of the insert operation.
  • 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. This method will insert all documents in the list into the MongoDB collection in one operation.

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, we use await before calling InsertManyAsync, ensuring that the operation completes before moving on to the next line of code. This is especially important in web applications or services where blocking the main thread could lead to poor performance or user experience.


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. Use Indexes: Indexes can significantly improve the insert performance by speeding up the search for the correct position to insert the new document. Ensure that you have appropriate indexes defined on the fields commonly used for insertion.
  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. Write Concern: The default write concern in MongoDB is Acknowledged, which waits for an acknowledgment from the server. If you are performing bulk insertions and do not require immediate acknowledgment, you can set a lower write concern to improve performance.
  5. Consider Asynchronous Operations: Asynchronous operations can improve the responsiveness of your application by allowing multiple insert operations to be executed concurrently.

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!

      • RackNerd: Cheap VPS hosting options that I love for low-resource usage!
      • Contabo: Alternative VPS hosting options with very affordable prices!
      • ConvertKit: This is the platform that I use for my newsletter!
      • SparkLoop: This service helps me add different value to my newsletter!
      • Opus Clip: This is what I use for help creating my short-form videos!
      • Newegg: For all sorts of computer components!
      • Bulk Supplements: For an enormous selection of health supplements!
      • Quora: I try to answer questions on Quora when folks request them of me!


    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. Additionally, creating appropriate indexes on the collection can improve insert performance. It’s important to optimize the insertion process based on the specific requirements of your application.

    author avatar
    Nick Cosentino Principal Software Engineering Manager
    Principal Software Engineering Manager at Microsoft. Views are my own.

    Leave a Reply