This is quick post on getting up and running with MongoDB using the “Official MongoDB C# driver” and both creating a database and adding some data to it.
- Using Nuget, add the “Official MongoDB C# driver” from 10gen to your project
- Add the following using clauses
12
using
MongoDB.Bson;
using
MongoDB.Driver;
-
Create a POCO object to represent the data you want to persist. The key thing to remember is to add a property of type ObjectId without this we’ll get and exception stating “No IdGenerator found”.
So an example POCO might look like this
1234567public
class
Person
{
public
ObjectId Id {
get
;
set
; }
public
string
FirstName {
get
;
set
; }
public
string
LastName {
get
;
set
; }
public
int
Age {
get
;
set
; }
}
-
Now we need to connect to the server and create/use a database.
123
MongoClient client =
new
MongoClient();
MongoServer server = client.GetServer();
MongoDatabase db = server.GetDatabase(
"MyDatabase"
);
Obviously the first two lines create a mongo client and then gets access to the server. The line server.GetDatabase(“MyDatabase”) will get the database (if it exists) but also create a database if it doesn’t exist.
Note: if you are creating a database using GetDatabase it will not exist until you actually store data in it.
-
Next we’re going to assume we want to store a collection of employees (a collection of Person objects). So we want to get the collection of “employees”. Like the creating of the database, if no employees currently exist we still get a collection object which we can then save data to.
1
MongoCollection<Person> collection = db.GetCollection<Person>(
"employees"
);
-
Let’s now create a Person object ready for adding to the collection and ultimately to the database.
Create the following
1234567Person p =
new
Person
{
Id = ObjectId.GenerateNewId(),
FirstName =
"Bob"
,
LastName =
"Baker"
,
Age = 36
}
Notice that we generate the Id using ObjectId.GenerateNewId().
-
Our next step is to save the new Person to the collection and this will add the data to the collection and thus the database, thus we can then query for this data afterwards using the JavaScript shell.
1
collection.Save(p);