MongoDB Magic a.k.a simple database operations


This is my little post on how to do simple database operations with MongoDB.

First let’s start with needed MongoDB needed functionalities. The simplest way is to open Visual Studio and manage your projects nugets packages. Add these four nuggets to your projects. Notice that you do not necessary need the mongocshaprdiver, it’s a legacy driver. Add it only if you need it.


Next to be able to use the classes for handling MongoDB database operation include the following namespaces:

using MongoDB.Bson;
using MongoDB.Driver;

BSON is: “BSON is a binary serialization format used to store documents and make remote procedure calls in MongoDB” More info here:

Driver is: “The official MongoDB C#/.NET Driver provides asynchronous interaction with MongoDB” More Info:

To code below will create a client connection to the MondoDB and will get a database in it.

var client = new MongoClient("mongodb://localhost:27017");
 var database = client.GetDatabase("databaseName");

To list all collections in a database:

foreach (var item in database.ListCollectionsAsync().Result.ToListAsync<BsonDocument>().Result)


To get the name of the collection:

var name = item.Elements.FirstOrDefault().Value.RawValue as String;

To access a collection and all of its documents:

var collection = database.GetCollection<BsonDocument>(name);
// This filter simply means that all data is retrieved
 var filter = new BsonDocument();

 var documents = collection.Find(filter);
 foreach (var document in documents.ToEnumerable())

To check if a document has elements(fields) with a certain data type:

var dateTimeFields = document.Elements.Where(o => o.Value.BsonType == BsonType.DateTime);
foreach (var dateTimeField in dateTimeFields)

To update a document with certain values:

var updateFilter = Builders<BsonDocument>.Filter.Eq("_id", document.Elements.FirstOrDefault().Value);
 var value = BsonTypeMapper.MapToDotNetValue(dateTimeField.Value);
 var updateDefiniotion = Builders<BsonDocument>.Update.Set(dateTimeField.Name, BsonTypeMapper.MapToBsonValue(((DateTime)value).AddDays(3)));

 var result = collection.UpdateOne(updateFilter, updateDefiniotion);
 if (result.ModifiedCount > 0)
 // Success
 // No updates

Retrieving documents based on a filter and copying them into another collection + deleting from the original collection:

var timeEntriesIntoTheFuture = Builders<BsonDocument>.Filter.Gt(dateTimeField.Name, BsonTypeMapper.MapToBsonValue(DateTime.Now));
 var entries = sourceCollection.Find(timeEntriesIntoTheFuture);
if(entries.Count() > 0)
 foreach(var entry in entries.ToEnumerable())

Checking if a collection exists:

public static bool DoesCollectionExist(IMongoDatabase database, String collectionName)
 bool collectionExists = false;

 foreach (var item in database.ListCollectionsAsync().Result.ToListAsync<BsonDocument>().Result)
 var name = item.Elements.FirstOrDefault().Value.AsString;
 if (name.Contains(collectionName))
 collectionExists = true;

 return collectionExists;

Updating an element at a certain position:

var updateDefiniotion = Builders<BsonDocument>.Update.Set(firstDocument.ElementAt(1).Name, BsonTypeMapper.MapToBsonValue(DateTime.Now));

Inserting a document in a manually defined manner:

var dateTimeStampeValue = new BsonDocument()
{ "ResetDate", BsonTypeMapper.MapToBsonValue(DateTime.Now) }

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s