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#!
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!
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!
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.
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:
BsonDocument
object, which represents the document we want to insert.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:
await
with InsertOneAsync
. This tells the program to continue with other work that doesn’t depend on the completion of the insert operation.
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.
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.
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:
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!
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:
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!