SlideShare a Scribd company logo
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

More Related Content

PDF
Mongo db for c# developers
PDF
Mongo db for C# Developers
PDF
NDC London 2013 - Mongo db for c# developers
KEY
CouchDB on Android
TXT
Tipo virus espia con esto aprenderan a espiar a personas etc jeropas de mrd :v
PDF
Inside MongoDB: the Internals of an Open-Source Database
PDF
MongoDB Performance Tuning
PDF
Couchdb w Ruby'm
Mongo db for c# developers
Mongo db for C# Developers
NDC London 2013 - Mongo db for c# developers
CouchDB on Android
Tipo virus espia con esto aprenderan a espiar a personas etc jeropas de mrd :v
Inside MongoDB: the Internals of an Open-Source Database
MongoDB Performance Tuning
Couchdb w Ruby'm

What's hot (20)

KEY
Mongo db presentation
PDF
San Francisco Java User Group
KEY
Paris js extensions
PDF
Redis for the Everyday Developer
PDF
Apache CouchDB talk at Ontario GNU Linux Fest
PPTX
Mythbusting: Understanding How We Measure the Performance of MongoDB
PDF
Nodejs mongoose
PDF
はじめてのMongoDB
KEY
MongoDB
PPTX
Mongoose and MongoDB 101
PDF
BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
DOCX
Mongoose getting started-Mongo Db with Node js
PDF
Elastic search 검색
PDF
The Ring programming language version 1.7 book - Part 47 of 196
DOCX
Qtp Imp Script Examples
PPTX
Back to Basics: My First MongoDB Application
PPTX
Sequelize
PDF
Testing Web Applications with GEB
PDF
20110514 mongo dbチューニング
PPTX
Webinarserie: Einführung in MongoDB: “Back to Basics” - Teil 3 - Interaktion ...
Mongo db presentation
San Francisco Java User Group
Paris js extensions
Redis for the Everyday Developer
Apache CouchDB talk at Ontario GNU Linux Fest
Mythbusting: Understanding How We Measure the Performance of MongoDB
Nodejs mongoose
はじめてのMongoDB
MongoDB
Mongoose and MongoDB 101
BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
Mongoose getting started-Mongo Db with Node js
Elastic search 검색
The Ring programming language version 1.7 book - Part 47 of 196
Qtp Imp Script Examples
Back to Basics: My First MongoDB Application
Sequelize
Testing Web Applications with GEB
20110514 mongo dbチューニング
Webinarserie: Einführung in MongoDB: “Back to Basics” - Teil 3 - Interaktion ...
Ad

Similar to Introduction to the new official C# Driver developed by 10gen (20)

KEY
Welcome the Offical C# Driver for MongoDB
PPTX
Using MongoDB with the .Net Framework
PPTX
Webinar: What's new in the .NET Driver
ODP
Mongo db rev001.
PDF
Mongo db first steps with csharp
PPTX
Getting Started with MongoDB Using the Microsoft Stack
PDF
Webinar: What's new in the .NET Driver
KEY
C# Development (Sam Corder)
PDF
MongoDB Tokyo - Monitoring and Queueing
PDF
The MongoDB Driver for F#
PDF
Mongo db basics
PDF
10gen MongoDB Video Presentation at WebGeek DevCup
PDF
PDF
MongoDB Webtech conference 2010
PPTX
Kalp Corporate MongoDB Tutorials
PDF
MongoDB and Node.js
PDF
Fun Teaching MongoDB New Tricks
PPTX
Running Production MongoDB Lightning Talk
PPTX
Einführung in MongoDB
PPTX
Lessons Learned from Building a Multi-Tenant Saas Content Management System o...
Welcome the Offical C# Driver for MongoDB
Using MongoDB with the .Net Framework
Webinar: What's new in the .NET Driver
Mongo db rev001.
Mongo db first steps with csharp
Getting Started with MongoDB Using the Microsoft Stack
Webinar: What's new in the .NET Driver
C# Development (Sam Corder)
MongoDB Tokyo - Monitoring and Queueing
The MongoDB Driver for F#
Mongo db basics
10gen MongoDB Video Presentation at WebGeek DevCup
MongoDB Webtech conference 2010
Kalp Corporate MongoDB Tutorials
MongoDB and Node.js
Fun Teaching MongoDB New Tricks
Running Production MongoDB Lightning Talk
Einführung in MongoDB
Lessons Learned from Building a Multi-Tenant Saas Content Management System o...
Ad

More from MongoDB (20)

PDF
MongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
PDF
MongoDB SoCal 2020: Go on a Data Safari with MongoDB Charts!
PDF
MongoDB SoCal 2020: Using MongoDB Services in Kubernetes: Any Platform, Devel...
PDF
MongoDB SoCal 2020: A Complete Methodology of Data Modeling for MongoDB
PDF
MongoDB SoCal 2020: From Pharmacist to Analyst: Leveraging MongoDB for Real-T...
PDF
MongoDB SoCal 2020: Best Practices for Working with IoT and Time-series Data
PDF
MongoDB SoCal 2020: MongoDB Atlas Jump Start
PDF
MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]
PDF
MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2
PDF
MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...
PDF
MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!
PDF
MongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your Mindset
PDF
MongoDB .local San Francisco 2020: MongoDB Atlas Jumpstart
PDF
MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...
PDF
MongoDB .local San Francisco 2020: Aggregation Pipeline Power++
PDF
MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...
PDF
MongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep Dive
PDF
MongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & Golang
PDF
MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...
PDF
MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...
MongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
MongoDB SoCal 2020: Go on a Data Safari with MongoDB Charts!
MongoDB SoCal 2020: Using MongoDB Services in Kubernetes: Any Platform, Devel...
MongoDB SoCal 2020: A Complete Methodology of Data Modeling for MongoDB
MongoDB SoCal 2020: From Pharmacist to Analyst: Leveraging MongoDB for Real-T...
MongoDB SoCal 2020: Best Practices for Working with IoT and Time-series Data
MongoDB SoCal 2020: MongoDB Atlas Jump Start
MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]
MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2
MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...
MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!
MongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your Mindset
MongoDB .local San Francisco 2020: MongoDB Atlas Jumpstart
MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...
MongoDB .local San Francisco 2020: Aggregation Pipeline Power++
MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...
MongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep Dive
MongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & Golang
MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...
MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...

Recently uploaded (20)

PPTX
1. Introduction to Computer Programming.pptx
PPTX
Tartificialntelligence_presentation.pptx
PPTX
cloud_computing_Infrastucture_as_cloud_p
PDF
NewMind AI Weekly Chronicles – August ’25 Week III
PPTX
O2C Customer Invoices to Receipt V15A.pptx
PDF
TrustArc Webinar - Click, Consent, Trust: Winning the Privacy Game
PDF
1 - Historical Antecedents, Social Consideration.pdf
PPTX
TLE Review Electricity (Electricity).pptx
PPTX
observCloud-Native Containerability and monitoring.pptx
PDF
Enhancing emotion recognition model for a student engagement use case through...
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
DP Operators-handbook-extract for the Mautical Institute
PDF
A comparative study of natural language inference in Swahili using monolingua...
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
WOOl fibre morphology and structure.pdf for textiles
PDF
A contest of sentiment analysis: k-nearest neighbor versus neural network
PDF
Transform Your ITIL® 4 & ITSM Strategy with AI in 2025.pdf
PDF
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
PDF
Developing a website for English-speaking practice to English as a foreign la...
1. Introduction to Computer Programming.pptx
Tartificialntelligence_presentation.pptx
cloud_computing_Infrastucture_as_cloud_p
NewMind AI Weekly Chronicles – August ’25 Week III
O2C Customer Invoices to Receipt V15A.pptx
TrustArc Webinar - Click, Consent, Trust: Winning the Privacy Game
1 - Historical Antecedents, Social Consideration.pdf
TLE Review Electricity (Electricity).pptx
observCloud-Native Containerability and monitoring.pptx
Enhancing emotion recognition model for a student engagement use case through...
Programs and apps: productivity, graphics, security and other tools
DP Operators-handbook-extract for the Mautical Institute
A comparative study of natural language inference in Swahili using monolingua...
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
NewMind AI Weekly Chronicles - August'25-Week II
WOOl fibre morphology and structure.pdf for textiles
A contest of sentiment analysis: k-nearest neighbor versus neural network
Transform Your ITIL® 4 & ITSM Strategy with AI in 2025.pdf
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
Developing a website for English-speaking practice to English as a foreign la...

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

  • 1. Introduction to the 10gen C# DriverStarts at 12:30pm EST
  • 2. MongoDB C# DriverNew 10gen supported driverRobert StamLead Engineer C# Driver
  • 3. HighlightsFull featuredHigh performanceRapidly tracks new releases of MongoDBFully supported by 10gen
  • 4. Release Timelinev0.5 released October 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 References to: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 MongoDB database holds collections of BSON documentsA BSON document is a collection of elementsA BSON element has:a namea typea value
  • 9. BSON Object ModelA set of classes that represent a BSON document in memoryImportant classes:BsonDocumentBsonElementBsonValue (and its subclasses)BsonType (an enum)
  • 10. BsonValue subclassesOne subclass for each BsonTypeExamples:BsonInt32/BsonInt64BsonStringBsonDateTimeBsonArrayBsonDocument (embedded document)and more…
  • 11. Sample BsonDocument// using functional 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 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”);
  • 15. C# Driver ClassesMain classes: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)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
  • 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 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.
  • 20. 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
  • 21. 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)
  • 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)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
  • 29. Find (with query)var query = new BsonDocument { { “Author”, “Ernest Hemingway” }};var cursor = books.Find(query);foreach (var book in cursor) { // process book}
  • 30. 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));
  • 31. 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)}
  • 32. 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)}
  • 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 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);
  • 35. 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).
  • 36. Removevar query = Query.EQ(“Author”, “Ernest Hemingway”);SafeModeResult result = books.Remove(query);// alsobooks.RemoveAll();books.Drop();
  • 37. 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.
  • 38. 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 }
  • 39. 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”);
  • 42. 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))
  • 43. SafeMode at different levelsSafeMode options can be set atMongoServerMongoDatabaseMongoCollectionIndividual operationSafeMode options are set at the time the instance is created (required for thread safety)
  • 44. 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
  • 45. 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”);
  • 46. 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);
  • 47. Presentation Available OnlineSlides available at:http://www.slideshare.net/mongodbWebinar available at:http://www.10gen.com/webinars/csharp