Introduction to the 10gen C# DriverStarts at 12:30pm EST
MongoDB C# DriverNew 10gen supported driverRobert StamLead Engineer C# Driver
HighlightsFull featuredHigh performanceRapidly tracks new releases of MongoDBFully supported by 10gen
Release Timelinev0.5 released October 15, 2010v0.7 released November 3, 2010v0.9 releasing soonv1.0 releasing within 1-2 months
DownloadingBinaries:http://github.com/mongodb/mongo-csharp-driver/downloadsIn .zip and .msi formatsSource code:http://github.com/mongodb/mongo-csharp-driverDocumentation:http://www.mongodb.org/display/DOCS/Drivers
Adding ReferencesAdd References to:MongoDB.Bson.dllMongoDB.Driver.dllFrom where?C:\Program Files (x86)\MongoDB\...…\mongo-csharp-driver\Driver\bin\Debug
Namespacesusing MongoDB.Bson;using MongoDB.Driver;// sometimesusing MongoDB.Bson.IO;using MongoDB.Bson.Serialization;using MongoDB.Bson.DefaultSerializer;using MongoDB.Driver.Builders;
BSON DocumentA MongoDB database holds collections of BSON documentsA BSON document is a collection of elementsA BSON element has:a namea typea value
BSON Object ModelA set of classes that represent a BSON document in memoryImportant classes:BsonDocumentBsonElementBsonValue (and its subclasses)BsonType (an enum)
BsonValue subclassesOne subclass for each BsonTypeExamples:BsonInt32/BsonInt64BsonStringBsonDateTimeBsonArrayBsonDocument (embedded document)and more…
Sample BsonDocument// using functional constructionvar book = new BsonDocument(    new BsonElement(“Author”, “Ernest Hemingway”),    new BsonElement(“Title”,		“For Whom the Bell Tolls”));
Sample BsonDocument (continued)// using collection initializer syntaxvar book = new BsonDocument {    { “Author”, “Ernest Hemingway” },    { “Title”, “For Whom the Bell Tolls” }};// compiler converts that tovar book = new BsonDocument();book.Add(“Author”, “Ernest Hemingway”);book.Add(“Title”, “For Whom the Bell Tolls”);
Sample BsonDocument (continued)// using fluent interfacevar book = new BsonDocument()    .Add(“Author”, “Ernest Hemingway”)    .Add(“Title”, “For Whom the Bell Tolls”);
Accessing BSON Document ElementsBsonValue value = document[“name”];string author = book[“Author”].AsString;string author = (string) book[“Author”];string author = (string) book[“Author”, null];int year = book[“PublicationYear”].AsInt32;booloutOfPrint = book[“OutOfPrint”].AsBoolean;booloutOfPrint = book[“OutOfPrint”].ToBoolean();BsonElement element = document.GetElement(“name”);
C# Driver ClassesMain classes:MongoServerMongoDatabaseMongoCollectionMongoCursorThese top level classes are all thread safe.(MongoCursor is thread safe once frozen).
MongoServervar server = MongoServer.Create();// orvar url = “mongodb://localhost:27017”;var server = MongoServer.Create(url);One instance is created for each URL. Subsequent calls to Create with the same URL return the same instance.Not [Serializable], so don’t put in session state.
Connection Strings (URLs)Connection string format:mongodb://[credentials@]hosts[/[database][?options]]Examples:mongodb://server1mongodb://server1:27018mongodb://username:password@server1/employeesmongodb://server1,server2,server3mongodb://server1,server2,server3/?slaveok=truemongodb://localhost/?safe=true
/?optionsconnect=direct|replicasetreplicaset=name (implies connect=replicaset)slaveok=true|falsesafe=true|falsew=n (implies safe=true)wtimeout=ms (implies safe=true)fsync=true|false (implies safe=true)Documentation at:http://www.mongodb.org/display/DOCS/Connections
Connection ModesDirectIf multiple host names are provided they are tried in sequence until a match is foundReplica setMultiple host names are treated as a seed list. All hosts are contacted in parallel to find the current primary. The seed list doesn’t have to include all the members of the replica set. If the replica set name was provided it will be verified.
slaveokIf connect=directIf slaveok=true then it is OK if the server is not a primary (useful to connect directly to secondaries in a replica set)If connect=replicasetIf slaveok=true then all writes are sent to the primary and reads are distributed round-robin to the secondaries
Connection PoolsThe driver maintains one connection pool for each server it is connected toThe connections are shared among all threadsA connection is normally returned to the connection pool as soon as possible (there is a way for a thread to temporarily hold on to a connection)
MongoDatabaseMongoDatabase test = server["test"];// orMongoCredentials credentials =	new MongoCredentials(username, password);MongoDatabase test = server["test", credentials];// orMongoDatabase test = server[“test”, SafeMode.True];One instance is created for each combination of name, credentials and safemode. Subsequent calls with the same values return the same instance.
MongoCollectionMongoCollection<BsonDocument> books = test["books"];MongoCollection<BsonDocument> books =test.GetCollection("books");// orMongoCollection<Book> books =test.GetCollection<Book>("books");Book is default document type
MongoCollection (continued)var books = database[“books”, SafeMode.True];var books = database.GetCollection<Book>(    “books”, SafeMode.True);One instance is created for each combination of name, TDefaultDocument and safemode. Subsequent calls with the same values return the same instance.
Insertvar books = database[“books”];var book = new BsonDocument {    { “Author”, “Ernest Hemingway” },    { “Title”, “For Whom the Bell Tolls” }};SafeModeResult result = books.Insert(book);Returns a SafeModeResult (null if not using safemode). Consider using InsertBatch if inserting multiple documents.
Insert (using serialization)// Book is a class with Author and Title propertiesvar books = database.GetCollection<Book>(“books”);var book = new Book {    Author = “Ernest Hemingway”,    Title = “For Whom the Bell Tolls”};var result = books.Insert(book);The book instance will be serialized to a BSON document (see Serialization and DefaultSerializer).
FindOnevar books = database[“books”];var book = books.FindOne(); // returns BsonDocument
FindOne (using serialization)var books = database[“books”];var book = books.FindOneAs<Book>();    // returns Book instead of BsonDocumentorvar books = database.GetCollection<Book>(“books”);var book = books.FindOne(); // returns Book    // because Book is default document type
Find (with query)var query = new BsonDocument {    { “Author”, “Ernest Hemingway” }};var cursor = books.Find(query);foreach (var book in cursor) {    // process book}
Find (with Query builder)var query = Query.EQ(“Author”, “Ernest Hemingway”);var cursor = books.Find(query);foreach (var book in cursor) {    // process book}// a more complicated queryvar query = Query.And(Query.EQ(“Author”, “Ernest Hemingway”),    Query.GTE(“PublicationYear”, 1950));
Cursor optionsA cursor can be modified before being enumerated (before it is frozen)var query = Query.GTE(“PublicationYear”, 1950);var cursor = books.Find(query);cursor.Skip = 100;cursor.Limit = 10;foreach (var book in cursor) {    // process 10 books (first 100 skipped)}
Cursor options (fluent interface)var query = Query.GTE(“PublicationYear”, 1950);var cursor = books.Find(query);foreach (var book incursor.SetSkip(100).SetLimit(10)) {    // process 10 books (first 100 skipped)}// or even shortervar query = Query.GTE(“PublicationYear”, 1950);foreach (var book in books.Find(query).SetSkip(100).SetLimit(10)) {    // process 10 books (first 100 skipped)}
Updatevar query = Query.EQ(“Title”, “For Who”);var update = new BsonDocument {    { “$set”, new BsonDocument {        { “Title”, “For Whom the Bell Tolls” }    }}};SafeModeResult result = books.Update(query, update);
Update (using Update builder)var query = Query.EQ(“Title”, “For Who”);var update =Update.Set(“Title”, “For Whom the Bell Tolls”);SafeModeResult result = books.Update(query, update);
SaveIf it’s a new document calls Insert otherwise calls Updatevar query = Query.EQ(“Title”, “For Who”);var book = books.FindOne(query);book.Title = “For Whom the Bell Tolls”;SafeModeResult result = book.Save();How does Save know whether it’s a new document or not? (It looks at the _id value).
Removevar query = Query.EQ(“Author”, “Ernest Hemingway”);SafeModeResult result = books.Remove(query);// alsobooks.RemoveAll();books.Drop();
RequestStart/RequestDoneWhen a sequence of operations all need to occur on the same connection wrap the operations with calls to RequestStart/RequestDoneRequestStart is per threadFor the duration of the Request the thread holds and uses a single connection, which is not returned to the pool until RequestDone is calledCalls to RequestStart can be nested. The request ends when the nesting level reaches zero again.
RequestStart (continued)RequestStart and the using statementReturn value of RequestStart is a helper object that implements IDisposableRequestDone is called for you automatically when the using statement terminates    using (server.RequestStart(database)) {        // a series of related operations    }
RunCommandWrapper methods are provided for many commands, but you can always run them yourselfvar command =    new BsonDocument(“collstats”, “books”);CommandResult result = database.RunCommand(command);CommandResult result =server.RunAdminCommand(“buildinfo”);
Sample Command WrappersCreateCollectionDropCollectionEvalGetStatsValidate
More MongoCollection MethodsCountCreateIndex/EnsureIndex/DropIndexDistinctFindAndModify/FindAndRemoveGeoNearGroupMapReduce
SafeModeWrite operations can be followed by a call to GetLastError to verify that they succeededSafeMode examples:SafeMode.FalseSafeMode.TrueSafeMode.W2new SafeMode(3, TimeSpan.FromSeconds(1))
SafeMode at different levelsSafeMode options can be set atMongoServerMongoDatabaseMongoCollectionIndividual operationSafeMode options are set at the time the instance is created (required for thread safety)
SerializationC# classes are mapped to BSON documentsAutoMap:Public fields and propertiesLots of ways to customize serializationIBsonSerializableIBsonSerializer (call BsonSerializer.RegisterSerializer)Replace one or more default conventions[Bson…] Attributes (like DataContract)BsonClassMap.RegisterClassMap
GridFSMongoDB’s Grid file systemvar gridFS = database.GridFS;var fileInfo = gridFS.Upload(“filename”);gridFS.Download(“filename”);// orvar fileInfo = gridFS.Upload(stream, “remotename”);gridFS.Download(stream, “remotename”);
GridFS StreamsAllow you to treat files stored in GridFS as if they were local filesvar gridFS = database.GridFS;var stream = gridFS.Create(“remotename”);// stream implements .NET’s Stream API// more examplesvar stream = gridFS.OpenRead(“remotename”);var stream = gridFS.Open(“remotename”,FileMode.Append);
Presentation Available OnlineSlides available at:http://www.slideshare.net/mongodbWebinar available at:http://www.10gen.com/webinars/csharp

Introduction to the new official C# Driver developed by 10gen

  • 1.
    Introduction to the10gen C# DriverStarts at 12:30pm EST
  • 2.
    MongoDB C# DriverNew10gen supported driverRobert StamLead Engineer C# Driver
  • 3.
    HighlightsFull featuredHigh performanceRapidlytracks new releases of MongoDBFully supported by 10gen
  • 4.
    Release Timelinev0.5 releasedOctober 15, 2010v0.7 released November 3, 2010v0.9 releasing soonv1.0 releasing within 1-2 months
  • 5.
    DownloadingBinaries:http://github.com/mongodb/mongo-csharp-driver/downloadsIn .zip and.msi formatsSource code:http://github.com/mongodb/mongo-csharp-driverDocumentation:http://www.mongodb.org/display/DOCS/Drivers
  • 6.
    Adding ReferencesAdd Referencesto:MongoDB.Bson.dllMongoDB.Driver.dllFrom where?C:\Program Files (x86)\MongoDB\...…\mongo-csharp-driver\Driver\bin\Debug
  • 7.
    Namespacesusing MongoDB.Bson;using MongoDB.Driver;//sometimesusing MongoDB.Bson.IO;using MongoDB.Bson.Serialization;using MongoDB.Bson.DefaultSerializer;using MongoDB.Driver.Builders;
  • 8.
    BSON DocumentA MongoDBdatabase holds collections of BSON documentsA BSON document is a collection of elementsA BSON element has:a namea typea value
  • 9.
    BSON Object ModelAset of classes that represent a BSON document in memoryImportant classes:BsonDocumentBsonElementBsonValue (and its subclasses)BsonType (an enum)
  • 10.
    BsonValue subclassesOne subclassfor each BsonTypeExamples:BsonInt32/BsonInt64BsonStringBsonDateTimeBsonArrayBsonDocument (embedded document)and more…
  • 11.
    Sample BsonDocument// usingfunctional constructionvar book = new BsonDocument( new BsonElement(“Author”, “Ernest Hemingway”), new BsonElement(“Title”, “For Whom the Bell Tolls”));
  • 12.
    Sample BsonDocument (continued)//using collection initializer syntaxvar book = new BsonDocument { { “Author”, “Ernest Hemingway” }, { “Title”, “For Whom the Bell Tolls” }};// compiler converts that tovar book = new BsonDocument();book.Add(“Author”, “Ernest Hemingway”);book.Add(“Title”, “For Whom the Bell Tolls”);
  • 13.
    Sample BsonDocument (continued)//using fluent interfacevar book = new BsonDocument() .Add(“Author”, “Ernest Hemingway”) .Add(“Title”, “For Whom the Bell Tolls”);
  • 14.
    Accessing BSON DocumentElementsBsonValue value = document[“name”];string author = book[“Author”].AsString;string author = (string) book[“Author”];string author = (string) book[“Author”, null];int year = book[“PublicationYear”].AsInt32;booloutOfPrint = book[“OutOfPrint”].AsBoolean;booloutOfPrint = book[“OutOfPrint”].ToBoolean();BsonElement element = document.GetElement(“name”);
  • 15.
    C# Driver ClassesMainclasses:MongoServerMongoDatabaseMongoCollectionMongoCursorThese top level classes are all thread safe.(MongoCursor is thread safe once frozen).
  • 16.
    MongoServervar server =MongoServer.Create();// orvar url = “mongodb://localhost:27017”;var server = MongoServer.Create(url);One instance is created for each URL. Subsequent calls to Create with the same URL return the same instance.Not [Serializable], so don’t put in session state.
  • 17.
    Connection Strings (URLs)Connectionstring format:mongodb://[credentials@]hosts[/[database][?options]]Examples:mongodb://server1mongodb://server1:27018mongodb://username:password@server1/employeesmongodb://server1,server2,server3mongodb://server1,server2,server3/?slaveok=truemongodb://localhost/?safe=true
  • 18.
    /?optionsconnect=direct|replicasetreplicaset=name (implies connect=replicaset)slaveok=true|falsesafe=true|falsew=n(implies safe=true)wtimeout=ms (implies safe=true)fsync=true|false (implies safe=true)Documentation at:http://www.mongodb.org/display/DOCS/Connections
  • 19.
    Connection ModesDirectIf multiplehost names are provided they are tried in sequence until a match is foundReplica setMultiple host names are treated as a seed list. All hosts are contacted in parallel to find the current primary. The seed list doesn’t have to include all the members of the replica set. If the replica set name was provided it will be verified.
  • 20.
    slaveokIf connect=directIf slaveok=truethen it is OK if the server is not a primary (useful to connect directly to secondaries in a replica set)If connect=replicasetIf slaveok=true then all writes are sent to the primary and reads are distributed round-robin to the secondaries
  • 21.
    Connection PoolsThe drivermaintains one connection pool for each server it is connected toThe connections are shared among all threadsA connection is normally returned to the connection pool as soon as possible (there is a way for a thread to temporarily hold on to a connection)
  • 22.
    MongoDatabaseMongoDatabase test =server["test"];// orMongoCredentials credentials = new MongoCredentials(username, password);MongoDatabase test = server["test", credentials];// orMongoDatabase test = server[“test”, SafeMode.True];One instance is created for each combination of name, credentials and safemode. Subsequent calls with the same values return the same instance.
  • 23.
    MongoCollectionMongoCollection<BsonDocument> books =test["books"];MongoCollection<BsonDocument> books =test.GetCollection("books");// orMongoCollection<Book> books =test.GetCollection<Book>("books");Book is default document type
  • 24.
    MongoCollection (continued)var books= database[“books”, SafeMode.True];var books = database.GetCollection<Book>( “books”, SafeMode.True);One instance is created for each combination of name, TDefaultDocument and safemode. Subsequent calls with the same values return the same instance.
  • 25.
    Insertvar books =database[“books”];var book = new BsonDocument { { “Author”, “Ernest Hemingway” }, { “Title”, “For Whom the Bell Tolls” }};SafeModeResult result = books.Insert(book);Returns a SafeModeResult (null if not using safemode). Consider using InsertBatch if inserting multiple documents.
  • 26.
    Insert (using serialization)//Book is a class with Author and Title propertiesvar books = database.GetCollection<Book>(“books”);var book = new Book { Author = “Ernest Hemingway”, Title = “For Whom the Bell Tolls”};var result = books.Insert(book);The book instance will be serialized to a BSON document (see Serialization and DefaultSerializer).
  • 27.
    FindOnevar books =database[“books”];var book = books.FindOne(); // returns BsonDocument
  • 28.
    FindOne (using serialization)varbooks = database[“books”];var book = books.FindOneAs<Book>(); // returns Book instead of BsonDocumentorvar books = database.GetCollection<Book>(“books”);var book = books.FindOne(); // returns Book // because Book is default document type
  • 29.
    Find (with query)varquery = new BsonDocument { { “Author”, “Ernest Hemingway” }};var cursor = books.Find(query);foreach (var book in cursor) { // process book}
  • 30.
    Find (with Querybuilder)var query = Query.EQ(“Author”, “Ernest Hemingway”);var cursor = books.Find(query);foreach (var book in cursor) { // process book}// a more complicated queryvar query = Query.And(Query.EQ(“Author”, “Ernest Hemingway”), Query.GTE(“PublicationYear”, 1950));
  • 31.
    Cursor optionsA cursorcan be modified before being enumerated (before it is frozen)var query = Query.GTE(“PublicationYear”, 1950);var cursor = books.Find(query);cursor.Skip = 100;cursor.Limit = 10;foreach (var book in cursor) { // process 10 books (first 100 skipped)}
  • 32.
    Cursor options (fluentinterface)var query = Query.GTE(“PublicationYear”, 1950);var cursor = books.Find(query);foreach (var book incursor.SetSkip(100).SetLimit(10)) { // process 10 books (first 100 skipped)}// or even shortervar query = Query.GTE(“PublicationYear”, 1950);foreach (var book in books.Find(query).SetSkip(100).SetLimit(10)) { // process 10 books (first 100 skipped)}
  • 33.
    Updatevar query =Query.EQ(“Title”, “For Who”);var update = new BsonDocument { { “$set”, new BsonDocument { { “Title”, “For Whom the Bell Tolls” } }}};SafeModeResult result = books.Update(query, update);
  • 34.
    Update (using Updatebuilder)var query = Query.EQ(“Title”, “For Who”);var update =Update.Set(“Title”, “For Whom the Bell Tolls”);SafeModeResult result = books.Update(query, update);
  • 35.
    SaveIf it’s anew document calls Insert otherwise calls Updatevar query = Query.EQ(“Title”, “For Who”);var book = books.FindOne(query);book.Title = “For Whom the Bell Tolls”;SafeModeResult result = book.Save();How does Save know whether it’s a new document or not? (It looks at the _id value).
  • 36.
    Removevar query =Query.EQ(“Author”, “Ernest Hemingway”);SafeModeResult result = books.Remove(query);// alsobooks.RemoveAll();books.Drop();
  • 37.
    RequestStart/RequestDoneWhen a sequenceof operations all need to occur on the same connection wrap the operations with calls to RequestStart/RequestDoneRequestStart is per threadFor the duration of the Request the thread holds and uses a single connection, which is not returned to the pool until RequestDone is calledCalls to RequestStart can be nested. The request ends when the nesting level reaches zero again.
  • 38.
    RequestStart (continued)RequestStart andthe using statementReturn value of RequestStart is a helper object that implements IDisposableRequestDone is called for you automatically when the using statement terminates using (server.RequestStart(database)) { // a series of related operations }
  • 39.
    RunCommandWrapper methods areprovided for many commands, but you can always run them yourselfvar command = new BsonDocument(“collstats”, “books”);CommandResult result = database.RunCommand(command);CommandResult result =server.RunAdminCommand(“buildinfo”);
  • 40.
  • 41.
  • 42.
    SafeModeWrite operations canbe followed by a call to GetLastError to verify that they succeededSafeMode examples:SafeMode.FalseSafeMode.TrueSafeMode.W2new SafeMode(3, TimeSpan.FromSeconds(1))
  • 43.
    SafeMode at differentlevelsSafeMode options can be set atMongoServerMongoDatabaseMongoCollectionIndividual operationSafeMode options are set at the time the instance is created (required for thread safety)
  • 44.
    SerializationC# classes aremapped to BSON documentsAutoMap:Public fields and propertiesLots of ways to customize serializationIBsonSerializableIBsonSerializer (call BsonSerializer.RegisterSerializer)Replace one or more default conventions[Bson…] Attributes (like DataContract)BsonClassMap.RegisterClassMap
  • 45.
    GridFSMongoDB’s Grid filesystemvar gridFS = database.GridFS;var fileInfo = gridFS.Upload(“filename”);gridFS.Download(“filename”);// orvar fileInfo = gridFS.Upload(stream, “remotename”);gridFS.Download(stream, “remotename”);
  • 46.
    GridFS StreamsAllow youto treat files stored in GridFS as if they were local filesvar gridFS = database.GridFS;var stream = gridFS.Create(“remotename”);// stream implements .NET’s Stream API// more examplesvar stream = gridFS.OpenRead(“remotename”);var stream = gridFS.Open(“remotename”,FileMode.Append);
  • 47.
    Presentation Available OnlineSlidesavailable at:http://www.slideshare.net/mongodbWebinar available at:http://www.10gen.com/webinars/csharp