Introduction
MongoDb is the open source document oriented database. This is a NoSql database. It stores the data in the JSON format (store dynamic content in BSON format). This article will explain the step by step process to implement the CRUD operations in MongoDB via .NET.
Background
These are defined nu-get packages that have been developed by the MongoDb team to connect and perform the operation on the MongoDB. These packages have predefined wide range of classes which we are going to utilize to interact with MongoDB.
Using the Code
As a first step, we need to install the MongoDb Nuget packages from the nuget. Below are the packages which need to be added in the .NET solution.
MongDB.Bson
MongoDB.Driver
MongoDB.Driver.Core
The classes under these packages will take care of most of the developer work like opening and closing the connection, maintaining the pool, etc. So it will make our .NET code more readable and maintainable.
BSON stands for Binary JSON, is a binary-encoded serialization of JSON-like documents. Like JSON, BSON supports the embedding of documents and arrays within other documents and arrays. Here is a white paper published on the JSON and BSON.
Create (Insert) Document
For insertion on single document, we can use the below code. Note before running this code that MongoDB instance should be up and running. You can also change the connection string to point your MongoDB server. Here, we are getting the test
database from MongoDB and adding a BsonDocument
into the people
table. Whenever we do not know the exact table collection type, we can use the BSONDocument
type. After creating a document, we are adding it in people
collection by calling InsertOneAsync
method. This method will only add one document in the table.
static async Task MainAsync(string[] args)
{
var ConnectionString = "mongodb://localhost:27017";
var client = new MongoClient(ConnectionString);
var db = client.GetDatabase("test");
var col = db.GetCollection<BsonDocument>("people");
var doc = new BsonDocument
{
{"Name" ,"test" },
{ "Age" , 33 }
};
await col.InsertOneAsync(doc);
}
For adding more than one document, we can use the below code. Here, as above, we are creating two BsonDocuments
and adding them into the table collection using InsertManyAsync
method.
static async Task MainAsync(string[] args)
{
var ConnectionString = "mongodb://localhost:27017";
var client = new MongoClient(ConnectionString);
var db = client.GetDatabase("test");
var col = db.GetCollection<BsonDocument>("people");
var doc = new BsonDocument
{
{"Name" ,"test" },
{ "Age" , 33 }
};
var doc2 = new BsonDocument
{
{ "Name" , "Hi"},
{"Profession" , "PM" }
};
await col.InsertManyAsync(new[] { doc, doc2 });
}
Instead of BsonDocument
, we can add our own class type document. We need to create a class and create that class type document and add in the similar fashion.
Retrieve Document
We can do it in two ways. The first way using cursor is the most effective way to do this. Cursors are how Mongo driver and server are going to talk with each other and server sends them back in batches. Below is the code that will get the document from the people
collection.
static async Task MainAsync(string[] args)
{
var ConnectionString = "mongodb://localhost:27017";
var client = new MongoClient(ConnectionString);
var db = client.GetDatabase("test");
var col = db.GetCollection<BsonDocument>("people");
using (var cursor = await col.Find(new BsonDocument()).ToCursorAsync())
{
while (await cursor.MoveNextAsync())
{
foreach (var doc in cursor.Current)
{
Console.WriteLine(doc);
}
}
}
}
There is one more way to retrieve the data from database. Which is much easier and cleaner and quicker. However, it will keep all the documents in memory so it may not be idle for some scenarios. But it will be useful many times when you know there are one or several documents in your collection.
static async Task MainAsync(string[] args)
{
var ConnectionString = "mongodb://localhost:27017";
var client = new MongoClient(ConnectionString);
var db = client.GetDatabase("test");
var col = db.GetCollection<BsonDocument>("people");
var list = await col.Find(new BsonDocument()).ToListAsync();
foreach (var doc in list)
{
Console.WriteLine(doc);
}
}
The above two ways show how we can retrieve all documents from a collection. If we want to retrieve a specific document, we can use the filter and all the documents which meet the condition will be returned. There is builder helper class which can be used to create a Filter.
Update
This is further divided in two categories, Replace
and Update
. So first, see how we can replace a document in MongoDB. When we replace a document, we cannot replace the ID
field.
static async Task MainAsync(string[] args)
{
var ConnectionString = "mongodb://localhost:27017";
var client = new MongoClient(ConnectionString);
var db = client.GetDatabase("test");
var col = db.GetCollection<BsonDocument>("people");
await col.ReplaceOneAsync(new BsonDocument("name", "Simon"),
new BsonDocument("name", "Juli"));
await col.Find(new BsonDocument()).ForEachAsync(X => Console.WriteLine(X));
}
The above code will replace change the name from Simon
to Juli
in the people collection.
Here is another sample code updating the records on the condition. Here, it is increasing the Age
by 10
of the person whose name is "Simon
".
static async Task MainAsync(string[] args)
{
var ConnectionString = "mongodb://localhost:27017";
var client = new MongoClient(ConnectionString);
var db = client.GetDatabase("test");
var col = db.GetCollection<BsonDocument>("people");
await col.UpdateOneAsync(Builders<BsonDocument>.Filter.Eq("name", "Simon"),
Builders<BsonDocument>.Update.Inc("Age", 10));
await col.Find(new BsonDocument()).ForEachAsync(X => Console.WriteLine(X));
}
In the same way, we can also use the UpdateManyAsync
method to update more than one document.
Delete
There are two methods for deleting the record from the MongoDB. DeleteManyAsync
and DeleteOneAsync
. As the name says, one is used to delete single record whereas the other one for deleting multiple records.
Below is the sample code to remove the document from people collection where name is Simon
.
await col.DeleteOneAsync(Builders<BsonDocument>.Filter.Eq("name" ,"test1"));
Note: Before we run all the above code, the MongoDB server instance should be up and running.
Hope this helps the .NET developer to work with MongoDB.
History
- 2nd October, 2016: Initial version