Quick Start: C# and MongoDB - Creating Documents

Ken W. Alger

#C#/.NET

In a previous post, I showed how to get C# and MongoDB connected. It is pretty straightforward to use the MongoDB.Driver from NuGet to establish a connection to a MongoDB server. In the case of this blog series, I'm using C# to connect to a MongoDB Atlas cluster that has the free demo data installed. With a connection established, let's see how to use C# to do Create operations in MongoDB.

Series Tools & Versions

The tools and versions I'm using for this series are:

  • MongoDB Atlas with an M0 free cluster
  • MongoDB Sample Dataset loaded, specifically the sample_training and grades dataset.
  • Windows 10
  • Visual Studio Community 2019
  • NuGet packages
  • MongoDB C# Driver (MongoDB.Driver), version 2.9.1
  • MongoDB BSON Library (MongoDB.Bson), version 2.9.1

Data

MongoDB stores data in JSON Documents. Actually, they are stored as Binary JSON (BSON) objects on disk, but that's a subject for another blog post. In our sample dataset, there is a sample_training with a grades collection. Here's what a sample document in that collection looks like:

{
    "_id": { "$oid":"56d5f7eb604eb380b0d8d8ce" },
    "student_id":{ "$numberDouble": "0" },
    "scores":[
        {"type":"exam","score": {"$numberDouble": "78.40446309504266" }},
        {"type":"quiz","score": {"$numberDouble": "73.36224783231339" }},
        {"type":"homework","score": {"$numberDouble": "46.980982486720535" }},
        {"type":"homework","score": {"$numberDouble": "76.67556138656222" }}
    ],
    "class_id":{"$numberDouble": "339"}
}

Connecting to a Specific Collection

There are 10,000 students in this collection, 0-9,999. Let's add one more by using C#. To do this, we'll need to use another package from NuGet, MongoDB.Bson. I'll start a new Solution in Visual Studio and call it MongoDBCRUDExample. I'll install the MongoDB.Bson and MongoDB.Driver packages and use the connection string provided from MongoDB Atlas. Next, I'll access our specific database and collection, sample_training and grades, respectively.

using System;
using MongoDB.Bson;
using MongoDB.Driver;

namespace MongoDBCRUDExample {
    class Program {
        static void Main (string[] args) {
            MongoClient dbClient = new MongoClient ( << YOUR ATLAS CONNECTION STRING >>);

            var database = dbClient.GetDatabase ("sample_training");
            var collection = database.GetCollection<BsonDocument> ("grades");

        }
    }
}

Creating a BSON Document

The collection variable is now our key reference point to our data. Since we are using a BsonDocument when assigning our collection variable, I've indicated that I'm not going to be using a pre-defined schema. This utilizes the power and flexibility of MongoDB's document model. I could define a plain-old-C#-object (POCO) to more strictly define a schema. I'll take a look at that option in a future post. For now, I'll create a new BsonDocument to insert into the database.

        var document = new BsonDocument { { "student_id", 10000 }, {
                "scores",
                new BsonArray {
                new BsonDocument { { "type", "exam" }, { "score", 88.12334193287023 } },
                new BsonDocument { { "type", "quiz" }, { "score", 74.92381029342834 } },
                new BsonDocument { { "type", "homework" }, { "score", 89.97929384290324 } },
                new BsonDocument { { "type", "homework" }, { "score", 82.12931030513218 } }
                }
                }, { "class_id", 480 }
        };

Create Operation

Then to Create the document in the sample_training.grades collection, we can do an insert operation.

        collection.InsertOne(document);

If you need to do that insert asynchronously, the MongoDB C# driver is fully async compatible. The same operation could be done with:

        await collection.InsertOneAsync (document);

If you have a need to insert multiple documents at the same time, MongoDB has you covered there as well with the InsertMany or InsertManyAsync methods.

Wrapping Up

We've seen how to structure a BSON Document in C# and then Create it inside a MongoDB database. The MongoDB C# Driver makes it easy to do with the InsertOne(), InsertOneAsync(), InsertMany(), or InsertManyAsync() methods. As I mentioned, using a BSONDocument is convenient when a schema isn't defined. More frequently, however, the schema is defined in our code, not in the database itself. I'll take a look at mapping BSON data to a C# Class in an upcoming post.

Now that we have Created data, we'll want to Read it. I'll show that step in the CRUD process in my next post.

Get started with an M0 cluster on MongoDB Atlas today. It's free forever and you'll be able to work alongside this blog series.

Previous articles in this Quick Start C# and MongoDB series: