DEV Community

Cover image for MongoDB in C#: Simplified Guide For Inserting Data
Dev Leader
Dev Leader

Posted on • Originally published at devleader.ca

MongoDB in C#: Simplified Guide For Inserting Data

MongoDB in C#: Simplified Guide For Inserting Data appeared first on Dev Leader.

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

Dev Leader Weekly | Substack

My weekly newsletter that simplifies software engineering for you, along with C# code examples. Join thousands of software engineers from companies like Microsoft and Amazon who are already reading! Click to read Dev Leader Weekly, a Substack publication with thousands of subscribers.

favicon weekly.devleader.ca

Overview of MongoDB in CSharp

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


Inserting Documents into MongoDB in CSharp

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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!


Wrapping Up MongoDB in CSharp

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!


Want More Dev Leader Content?

  • Follow along on this platform if you haven’t already!
  • Subscribe to my free weekly software engineering and dotnet-focused newsletter. I include exclusive articles and early access to videos: SUBSCRIBE FOR FREE
  • Looking for courses? Check out my offerings: VIEW COURSES
  • E-Books & other resources: VIEW RESOURCES
  • Watch hundreds of full-length videos on my YouTube channel: VISIT CHANNEL
  • Visit my website for hundreds of articles on various software engineering topics (including code snippets): VISIT WEBSITE
  • Check out the repository with many code examples from my articles and videos on GitHub: VIEW REPOSITORY

Dev Leader Weekly | Substack

My weekly newsletter that simplifies software engineering for you, along with C# code examples. Join thousands of software engineers from companies like Microsoft and Amazon who are already reading! Click to read Dev Leader Weekly, a Substack publication with thousands of subscribers.

favicon weekly.devleader.ca

Top comments (0)