MongoDB is a NoSQL database. In this post, I will explain how to use the C#/.NET driver for MongoDB. The MongoDB C# Driver is the 10gen-supported.
Installing MongoDB ( Windows )
You can download MongoDb from the link: http://www.mongodb.org/downloads
After you install, go to INSTALL_DIR/bin directory and run “mongod.exe”. This will start the database.
Now start “mongo.exe” which is in the same directory. A javascript shell will be opened. By default a database named ‘test’ is created by MongoDB installation.
Some helpfull commands:
> show dbs
…
> show collections
…
> db.MyNewDatabaseName.insert( { name: “John”, age: 12 } )
//MyNewDatabaseName is created automatically and the object with name = ‘John’ and age = 12 inserted into it.
> db.MyNewDatabaseName.find()
//This command returns all documents in our database in json format.
C#/.NET Driver
You can install the driver from http://github.com/mongodb/mongo-csharp-driver/downloads
Add reference to the “MongoDB.Bson.dll” and “MongoDB.Driver.dll” .
The API docs is available on web: http://api.mongodb.org/csharp/current/
We are ready to connect our MongoDB server(s) do some CRUD operations.
Creating a MongoServer object: ( by default the port 27017 is used by MongoDB )
string url = “mongodb://localhost:27017”;
MongoServer server = MongoServer.Create(url);
MongoDatabase testDb = server[“test”, SafeMode.True];
MongoCollection<BsonDocument> collection = testDb[“MyNewDatabase”, SafeMode.True];
From now on we are just going to do operations on the collection object. We connect to the “MyNewDatabase” with safe mode on. This feature is needed if you want to check whether your operation has succeeded or failed. When SafeMode=true, driver queries the database for LastErrorMessage. Otherwise, It does not make this query after your operation completed.
Our collection object is BsonDocument type. So we are going to insert BsonDocuments into it:
SafeModeResult result = collection.Insert(new BsonDocument { { “Name”, “John”}, { “Age”, 15 } } );
After you insert some more documents to the database try the following query:
var query = Query.Or(Query.EQ(“Name”, “John”), Query.GTE(“Age”, 20));
var cursor = collection.Find(query);
foreach (var item in cursor)
{ //do something with item
}
The examples were for BsonDocument objects. How about our custom objects. Let us have Person objects and we want to store and query them in MongoDB.
MongoCollection<Person> collection = testDb.GetCollection<Person>(“MyPersonDatabase”, SafeMode.True);
collection.Insert(new Person(“John”, 38));
That’s it. We do not need to add any attribute to Person class. It just have two fields name and age.
We inserted our object successfully. We can check this by running “mongo.exe” and type:
>db. MyPersonDatabase.find()
{ “_id”: Objectid(“4f296e1e2d4ce5510645ac61”), “Name” : “John”, “Age” : 38 }
The “_id” field is generated and inserted as objectid of our object. If you try to select this record from database:
Person p = collection.FindOne();
You get an error says “_id” field is missing and it can not deserialize the Person object.
I come up with a quick solution which is to add _id field to our Person object. There can be other solutions.
Updating objects is also simple:
Person p = collection.FindOne();
p.Age++;
collection.Save(p);
You can also use GridFS feature of MongoDB from the driver API. You can download/upload files or streams to MongoDB server.
var gridFileSystem = test1.GridFS;
//Upload . stream is source
var fileInfo = gridFileSystem.Upload(stream, remoteFileName);
//Download. stream is destination
gridFileSystem.Download(stream, remoteFileName);
References:
http://www.slideshare.net/mongodb
https://www.10gen.com/presentations#programming_lang__dotnet
https://www.10gen.com/presentations/mongosf-2011/c-sharp-development-with-mongodb