Sunday, April 1, 2012

C# and MongoDb tips – Part 1


Establish a server instance
Create method is used to obtain an instance of MongoServer by passing a valid connection string:
[TestMethod]
public void CreateMethodCreatesOpensAServerConnection()
{
    const string connectionString = "mongodb://localhost";
    var server = MongoServer.Create(connectionString);

    Assert.IsTrue(server.DatabaseExists("test"));
}
Connecting to a database
You can navigate from an instance of MongoServer to an instance of MongoDatabase  using one of the GetDatabase method
private static MongoServer GetMongodbServer()
{
    const string connectionString = "mongodb://localhost";
    var server = MongoServer.Create(connectionString);
    return server;
}

[TestMethod]
public void CreateDatabaseShouldOpenADatabaseWithTheCredentialsPassed()
{
    var server = GetMongodbServer();
    var databaseSettings = server.CreateDatabaseSettings("sampleDb");
    databaseSettings.SlaveOk = true;
    databaseSettings.Credentials = new MongoCredentials("admin", "pass@word1");
    var database = server.GetDatabase(databaseSettings);
    Assert.IsTrue(database.Name == "sampleDb");
}

Inserting values to a collection
To insert a document in the collection create an object representing the document and call Insert. The object can be an instance of BsonDocument or of any class that can be successfully serialized as a BSON document. You can insert more than one document at a time using the InsertBatch method.
[TestMethod]
public void InsertAndInsertBatchShouldInsertValuesToACollection()
{
    var database = GetDatabaseInstance();
           
    var server = database.Server;

    using (server.RequestStart(database))
    {
        if (database.CollectionExists("Employees"))
            database.DropCollection("Employees");
               
        database.CreateCollection("Employees");

        var collectionSettings = database.CreateCollectionSettings<Employee>("Employees");
        collectionSettings.SlaveOk = true;
        var employees = database.GetCollection(collectionSettings);

        var employeesToAdd = new List<Employee>
                                {
                                    new Employee {Id = 1, FirstName = "Mike", LastName = "Pagel", DoJ = new DateTime(1990, 10, 1)},
                                    new Employee {Id = 2, FirstName = "Steve", LastName = "John", DoJ = new DateTime(1990, 10, 1)},
                                    new Employee {Id = 3, FirstName = "Betty", LastName = "Green", DoJ = new DateTime(1990, 10, 1)},
                                    new Employee {Id = 4, FirstName = "Mike", LastName = "Pagel", DoJ = new DateTime(1990, 10, 1)}
                                }.ToArray();
        employees.InsertBatch(employeesToAdd);
        Assert.IsTrue(employees.FindAllAs<Employee>().Any(x => x.FirstName == "Betty"));
    }           
}

No comments: