Upload
lester-sims
View
230
Download
2
Embed Size (px)
Citation preview
Using MongoDB from C#
A brief introduction
MongoDB drivers
• To use MongoDB from a programming language you need a driver• MongoDB has drivers for a number of languages, including• C#• Java• Node.js• PHP• http://docs.mongodb.org/ecosystem/drivers/
Visual Studio: Getting the right NuGet packages• Several MongoDB drivers for C#• I use• Official MongoDB C# driver
• The easiest way to get the driver is with NuGet• Right click you project in Visual Studio• Select Manage NuGet packages• Search for Mongo• Choose “Official MongoDB C# driver”
OOP vs. Documents
• Object Oriented Programming (C#)• Objects have a fixed schema defined by a class
• Documents (MongoDB)• Documents to not have a fixed schema
• The C# driver requires all documents to have the same structure• Fixed schema• With find(…)
• All document must have the same schema.• Otherwise you get some BSON serialization exception
• With insert(…) • If you omit some attributes they will be set to null in the document
Some methods from the driver
• MongoCursor<T> result = Collection.Find(query)• Ordinary find
• IQueryable<Book> books = from e in collection.AsQueryable() where … select e;• Find using LINQ syntax
• Collection.insert(someObject)• Inserts a new object. Giving it an ObjectId
• Collection.save(someObject)• Saves/update an existing object
• collection.Update(query, update)• Updates documents satisfying query.
• collection.Remove(query)• Removes documents satisfying query.
• WriteConcernResult• Returned by the changing methods. Has information about the status of the change
• Example• mongoBooks.cs, books2.cs (typed + un-typed examples)