Showing posts with label Mongodb. Show all posts
Showing posts with label Mongodb. Show all posts

Wednesday, April 4, 2012

C# and MongoDb tips – Part 4


Modifying a cursor
The Find method doesn’t immediately return the actual results of a query. Instead they return a cursor (MongoCursor) that can be enumerated to retrieve the results of the query. The query is sent to the server when we first try to retrieve the result. This feature allows the user to control the results of the query before fetching the results by modifying the cursor.
For e.g. you can use the skip, limit, sort properties to modify the cursor. You can also use the fluent interface methods for the properties to modify the cursor. After setting these properties, you can enumerate the results to get the actual output.
[TestMethod]
public void SkipAndLimitShouldReturnPagedDataFromACursor()
{
    var database = GetDatabaseInstance();
    var collectionSettings = database.CreateCollectionSettings<Employee>("Employees");
    collectionSettings.SlaveOk = true;
    var employees = database.GetCollection(collectionSettings);
    var employeeCursor = employees.FindAll();

    employeeCursor.Skip = 5;
    employeeCursor.Limit = 2;

    Assert.IsTrue(employeeCursor.ToList().Count == 2);
}

[TestMethod]
public void SkipAndLimitUsingFluentInterfacesShouldReturnPagedDataFromACursor()
{
    var database = GetDatabaseInstance();
    var collectionSettings = database.CreateCollectionSettings<Employee>("Employees");
    collectionSettings.SlaveOk = true;
    var employees = database.GetCollection(collectionSettings);
    var employeeCursor = employees.FindAll().SetSkip(5).SetLimit(2).SetSortOrder("FirstName", "LastName");
    Assert.IsTrue(employeeCursor.ToList().Count == 2);
}

Tuesday, April 3, 2012

C# and MongoDb tips – Part 3


Changing values in a collection
You can update/ save values in a collection using the Save, Update or FindAndModify methods. The Save method is a combination of Insert and Update. If the Id member of the document has a value, then it is assumed to be an existing document and Save calls Update on the document. Otherwise it is assumed to be a new document and Save calls Insert after first assigning a newly generated unique value to the Id member.
[TestMethod]
public void SaveShouldSaveTheChangedEntityToCollection()
{
    var database = GetDatabaseInstance();
    var collectionSettings = database.CreateCollectionSettings<Employee>("Employees");
    collectionSettings.SlaveOk = true;
    var employees = database.GetCollection(collectionSettings);
    var query = Query.And(Query.EQ("FirstName", "Betty"), Query.EQ("LastName", "Green"));
    var employee = employees.FindOne(query);
    employee.FirstName = "Rachel";
    employees.Save(employee);
    query = Query.And(Query.EQ("FirstName", "Rachel"), Query.EQ("LastName", "Green"));
    employee = employees.FindOne(query);
    Assert.IsTrue(employee != null && employee.FirstName == "Rachel");
}
The Update method is used to update existing documents.
 [TestMethod]
public void UpdateShouldUpdateTheChangedEntitiesMacthingTheQueryBuilderConditionToCollection()
{
    var database = GetDatabaseInstance();
    var collectionSettings = database.CreateCollectionSettings<Employee>("Employees");
    collectionSettings.SlaveOk = true;
    var employees = database.GetCollection(collectionSettings);
    var query = Query.And(Query.EQ("FirstName", "Rachel"), Query.EQ("LastName", "Green"));
    employees.Update(query, Update.Set("FirstName", "Betty"));
    query = Query.And(Query.EQ("FirstName", "Betty"), Query.EQ("LastName", "Green"));
    var employee = employees.FindOne(query);
    Assert.IsTrue(employee != null && employee.FirstName == "Betty");
}
FindAndModify always updates a single document, and you can combine a query that matches multiple documents with sort criteria that will determine exactly which matching document is updated. In addition, FindAndModify will return the matching documentsand if you wish you can specify which fields of the matching document to return.
[TestMethod]
public void FindAndModifyShouldFindAndModifyTheCollectionInAtomicOperation()
{
    var database = GetDatabaseInstance();
    var collectionSettings = database.CreateCollectionSettings<Employee>("Employees");
    collectionSettings.SlaveOk = true;
    var employees = database.GetCollection(collectionSettings);

    var query = Query.Or(Query.EQ("FirstName", "Mike"), Query.EQ("FirtName", "Steve"));
    var sortOrder = SortBy.Ascending("FirstName", "LastName");
    var update = Update.Set("DoJ", new DateTime(1995, 8, 1));
    var updatedEmployees = employees.FindAndModify(query, sortOrder, update, true);
    var employeesModified = updatedEmployees.GetModifiedDocumentAs<Employee>();

    Assert.IsTrue(employeesModified.DoJ.Date.Year == 1995);
}

C# and MongoDb tips – Part 2


Filtering a collection
To retrieve documents from a collection use one of the various Find methods. FindOne returns the first document it finds (when there are many documents in a collection you can't be sure which one it will be).
[TestMethod]
public void FindOneShouldReturnTheFirstEntryInTheCollection()
{
    var database = GetDatabaseInstance();
    var collectionSettings = database.CreateCollectionSettings<Employee>("Employees");
    collectionSettings.SlaveOk = true;
    var employees = database.GetCollection(collectionSettings);

    var firstEmployee = employees.FindOne();
    Assert.IsTrue(firstEmployee.Id != default(int));
}

If you want to read a document that is not of the type use the FindOneAs method, which allows you to override the type of the returned document.
[TestMethod]
public void FindOneAsShouldReturnTheFirstItemInTheCollectionOverridingTheTypeOfReturnedDocument()
{
    var database = GetDatabaseInstance();
    var employees = database.GetCollection("Employees");
    var employee = employees.FindOneAs(typeof (Employee));
    Assert.IsTrue(employee != null && employee is Employee);
}

The Find and FindAs methods take a query that tells the server which documents to return. The query parameter is of type IMongoQuery. IMongoQuery is a marker interface that identifies classes that can be used as queries. The most common ways to construct a query are to either use the Query builder class.
[TestMethod]
public void FindOneShouldReturnTheFirstItemInTheCollectionBasedOnQuery()
{
    var database = GetDatabaseInstance();
    var collectionSettings = database.CreateCollectionSettings<Employee>("Employees");
    collectionSettings.SlaveOk = true;
    var employees = database.GetCollection(collectionSettings);
    var queryDocument = new QueryDocument("FirstName", "Betty");
    var employee = employees.FindOne(queryDocument);
    Assert.IsTrue(employee != null && employee.FirstName == "Betty");
}

[TestMethod]
public void QueryBuilderCanBeUsedToFilterEntriesInCollection()
{
    var database = GetDatabaseInstance();
    var collectionSettings = database.CreateCollectionSettings<Employee>("Employees");
    collectionSettings.SlaveOk = true;
    var employees = database.GetCollection(collectionSettings);
    var query = Query.And(Query.EQ("FirstName", "Betty"), Query.EQ("LastName", "Green"));
    var employee = employees.FindOne(query);
    Assert.IsTrue(employee != null && employee.FirstName == "Betty");
}

[TestMethod]
public void FindReturnsAllEntriesMatchingTheQueryInTheCollection()
{
    var database = GetDatabaseInstance();
    var collectionSettings = database.CreateCollectionSettings<Employee>("Employees");
    collectionSettings.SlaveOk = true;
    var employees = database.GetCollection(collectionSettings);

    var query = Query.Or(Query.EQ("FirstName", "Betty"), Query.EQ("FirstName", "Prajeesh"));

    var employeeResult = employees.Find(query);
    Assert.IsTrue(employeeResult.All(e => e.FirstName == "Betty" || e.FirstName == "Prajeesh"));
}

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"));
    }           
}