SlideShare a Scribd company logo
1 of 47
Introduction to the 10gen C# DriverStarts at 12:30pm EST
MongoDB C# Driver New 10gen supported driver Robert Stam Lead Engineer C# Driver
Highlights Full featured High performance Rapidly tracks new releases of MongoDB Fully supported by 10gen
Release Timeline v0.5 released October 15, 2010 v0.7 released November 3, 2010 v0.9 releasing soon v1.0 releasing within 1-2 months
Downloading Binaries: http://github.com/mongodb/mongo-csharp-driver/downloads In .zip and .msi formats Source code: http://github.com/mongodb/mongo-csharp-driver Documentation: http://www.mongodb.org/display/DOCS/Drivers
Adding References Add References to: MongoDB.Bson.dll MongoDB.Driver.dll From where? C:rogram Files (x86)ongoDB.. …ongo-csharp-driverriverinebug
Namespaces using MongoDB.Bson; using MongoDB.Driver; // sometimes using MongoDB.Bson.IO; using MongoDB.Bson.Serialization; using MongoDB.Bson.DefaultSerializer; using MongoDB.Driver.Builders;
BSON Document A MongoDB database holds collections of BSON documents A BSON document is a collection of elements A BSON element has: a name a type a value
BSON Object Model A set of classes that represent a BSON document in memory Important classes: BsonDocument BsonElement BsonValue (and its subclasses) BsonType (an enum)
BsonValue subclasses One subclass for each BsonType Examples: BsonInt32/BsonInt64 BsonString BsonDateTime BsonArray BsonDocument (embedded document) and more…
Sample BsonDocument // using functional construction var book = new BsonDocument(     new BsonElement(“Author”, “Ernest Hemingway”),     new BsonElement(“Title”, 		“For Whom the Bell Tolls”) );
Sample BsonDocument (continued) // using collection initializer syntax var book = new BsonDocument {     { “Author”, “Ernest Hemingway” },     { “Title”, “For Whom the Bell Tolls” } }; // compiler converts that to var book = new BsonDocument(); book.Add(“Author”, “Ernest Hemingway”); book.Add(“Title”, “For Whom the Bell Tolls”);
Sample BsonDocument (continued) // using fluent interface var book = new BsonDocument()     .Add(“Author”, “Ernest Hemingway”)     .Add(“Title”, “For Whom the Bell Tolls”);
Accessing BSON Document Elements BsonValue 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 Classes Main classes: MongoServer MongoDatabase MongoCollection MongoCursor These top level classes are all thread safe. (MongoCursor is thread safe once frozen).
MongoServer var server = MongoServer.Create(); // or var 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://server1 mongodb://server1:27018 mongodb://username:password@server1/employees mongodb://server1,server2,server3 mongodb://server1,server2,server3/?slaveok=true mongodb://localhost/?safe=true
/?options connect=direct|replicaset replicaset=name (implies connect=replicaset) slaveok=true|false safe=true|false w=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 Modes Direct If multiple host names are provided they are tried in sequence until a match is found Replica set Multiple 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.
slaveok If connect=direct If 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=replicaset If slaveok=true then all writes are sent to the primary and reads are distributed round-robin to the secondaries
Connection Pools The driver maintains one connection pool for each server it is connected to The connections are shared among all threads A 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)
MongoDatabase MongoDatabase test = server["test"]; // or MongoCredentials credentials = 	new MongoCredentials(username, password); MongoDatabase test = server["test", credentials]; // or MongoDatabase 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.
MongoCollection MongoCollection<BsonDocument> books = test["books"]; MongoCollection<BsonDocument> books = test.GetCollection("books"); // or MongoCollection<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.
Insert var 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 properties var 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).
FindOne var 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 BsonDocument or var 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 query var query = Query.And( Query.EQ(“Author”, “Ernest Hemingway”),     Query.GTE(“PublicationYear”, 1950) );
Cursor options A 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 in cursor.SetSkip(100).SetLimit(10)) {     // process 10 books (first 100 skipped) } // or even shorter var query = Query.GTE(“PublicationYear”, 1950); foreach (var book in  books.Find(query).SetSkip(100).SetLimit(10)) {     // process 10 books (first 100 skipped) }
Update var 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);
Save If it’s a new document calls Insert otherwise calls Update var 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).
Remove var query = Query.EQ(“Author”, “Ernest Hemingway”); SafeModeResult result = books.Remove(query); // also books.RemoveAll(); books.Drop();
RequestStart/RequestDone When a sequence of operations all need to occur on the same connection wrap the operations with calls to RequestStart/RequestDone RequestStart is per thread For the duration of the Request the thread holds and uses a single connection, which is not returned to the pool until RequestDone is called Calls to RequestStart can be nested. The request ends when the nesting level reaches zero again.
RequestStart (continued) RequestStart and the using statement Return value of RequestStart is a helper object that implements IDisposable RequestDone is called for you automatically when the using statement terminates     using (server.RequestStart(database)) {         // a series of related operations     }
RunCommand Wrapper methods are provided for many commands, but you can always run them yourself var command =     new BsonDocument(“collstats”, “books”); CommandResult result = database.RunCommand(command); CommandResult result = server.RunAdminCommand(“buildinfo”);
Sample Command Wrappers CreateCollection DropCollection Eval GetStats Validate
More MongoCollection Methods Count CreateIndex/EnsureIndex/DropIndex Distinct FindAndModify/FindAndRemove GeoNear Group MapReduce
SafeMode Write operations can be followed by a call to GetLastError to verify that they succeeded SafeMode examples: SafeMode.False SafeMode.True SafeMode.W2 new SafeMode(3, TimeSpan.FromSeconds(1))
SafeMode at different levels SafeMode options can be set at MongoServer MongoDatabase MongoCollection Individual operation SafeMode options are set at the time the instance is created (required for thread safety)
Serialization C# classes are mapped to BSON documents AutoMap: Public fields and properties Lots of ways to customize serialization IBsonSerializable IBsonSerializer (call BsonSerializer.RegisterSerializer) Replace one or more default conventions [Bson…] Attributes (like DataContract) BsonClassMap.RegisterClassMap
GridFS MongoDB’s Grid file system var gridFS = database.GridFS; var fileInfo = gridFS.Upload(“filename”); gridFS.Download(“filename”); // or var fileInfo = gridFS.Upload(stream, “remotename”); gridFS.Download(stream, “remotename”);
GridFS Streams Allow you to treat files stored in GridFS as if they were local files var gridFS = database.GridFS; var stream = gridFS.Create(“remotename”); // stream implements .NET’s Stream API // more examples var stream = gridFS.OpenRead(“remotename”); var stream = gridFS.Open(“remotename”, FileMode.Append);
Presentation Available Online Slides available at: http://www.slideshare.net/mongodb Webinar available at: http://www.10gen.com/webinars/csharp

More Related Content

What's hot

San Francisco Java User Group
San Francisco Java User GroupSan Francisco Java User Group
San Francisco Java User Group
kchodorow
 
Apache CouchDB talk at Ontario GNU Linux Fest
Apache CouchDB talk at Ontario GNU Linux FestApache CouchDB talk at Ontario GNU Linux Fest
Apache CouchDB talk at Ontario GNU Linux Fest
Myles Braithwaite
 
Qtp Imp Script Examples
Qtp Imp Script ExamplesQtp Imp Script Examples
Qtp Imp Script Examples
User1test
 
Webinarserie: Einführung in MongoDB: “Back to Basics” - Teil 3 - Interaktion ...
Webinarserie: Einführung in MongoDB: “Back to Basics” - Teil 3 - Interaktion ...Webinarserie: Einführung in MongoDB: “Back to Basics” - Teil 3 - Interaktion ...
Webinarserie: Einführung in MongoDB: “Back to Basics” - Teil 3 - Interaktion ...
MongoDB
 

What's hot (20)

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

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

C# Development (Sam Corder)
C# Development (Sam Corder)C# Development (Sam Corder)
C# Development (Sam Corder)
MongoSF
 
Intro To Mongo Db
Intro To Mongo DbIntro To Mongo Db
Intro To Mongo Db
chriskite
 

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

Welcome the Offical C# Driver for MongoDB
Welcome the Offical C# Driver for MongoDBWelcome the Offical C# Driver for MongoDB
Welcome the Offical C# Driver for MongoDB
 
Scripting as a Second Language
Scripting as a Second LanguageScripting as a Second Language
Scripting as a Second Language
 
Using MongoDB with the .Net Framework
Using MongoDB with the .Net FrameworkUsing MongoDB with the .Net Framework
Using MongoDB with the .Net Framework
 
Mongo db rev001.
Mongo db rev001.Mongo db rev001.
Mongo db rev001.
 
Microsrvs testing-slides
Microsrvs testing-slidesMicrosrvs testing-slides
Microsrvs testing-slides
 
C# Development (Sam Corder)
C# Development (Sam Corder)C# Development (Sam Corder)
C# Development (Sam Corder)
 
A single language for backend and frontend from AngularJS to cloud with Clau...
A single language for backend and frontend  from AngularJS to cloud with Clau...A single language for backend and frontend  from AngularJS to cloud with Clau...
A single language for backend and frontend from AngularJS to cloud with Clau...
 
A single language for backend and frontend from AngularJS to cloud with Clau...
A single language for backend and frontend  from AngularJS to cloud with Clau...A single language for backend and frontend  from AngularJS to cloud with Clau...
A single language for backend and frontend from AngularJS to cloud with Clau...
 
Concurrency at the Database Layer
Concurrency at the Database Layer Concurrency at the Database Layer
Concurrency at the Database Layer
 
Replacing Oracle with MongoDB for a templating application at the Bavarian go...
Replacing Oracle with MongoDB for a templating application at the Bavarian go...Replacing Oracle with MongoDB for a templating application at the Bavarian go...
Replacing Oracle with MongoDB for a templating application at the Bavarian go...
 
Rails vu d'un Javaiste
Rails vu d'un JavaisteRails vu d'un Javaiste
Rails vu d'un Javaiste
 
ElasticSearch for .NET Developers
ElasticSearch for .NET DevelopersElasticSearch for .NET Developers
ElasticSearch for .NET Developers
 
MongoDB Munich 2012: MongoDB for official documents in Bavaria
MongoDB Munich 2012: MongoDB for official documents in BavariaMongoDB Munich 2012: MongoDB for official documents in Bavaria
MongoDB Munich 2012: MongoDB for official documents in Bavaria
 
Building Your First MongoDB App
Building Your First MongoDB AppBuilding Your First MongoDB App
Building Your First MongoDB App
 
Getting Started with Microsoft Bot Framework
Getting Started with Microsoft Bot FrameworkGetting Started with Microsoft Bot Framework
Getting Started with Microsoft Bot Framework
 
Intro To Mongo Db
Intro To Mongo DbIntro To Mongo Db
Intro To Mongo Db
 
Php introduction
Php introductionPhp introduction
Php introduction
 
MongoDB & Mongoid with Rails
MongoDB & Mongoid with RailsMongoDB & Mongoid with Rails
MongoDB & Mongoid with Rails
 
Painless Data Storage with MongoDB & Go
Painless Data Storage with MongoDB & Go Painless Data Storage with MongoDB & Go
Painless Data Storage with MongoDB & Go
 
Apache Beam de A à Z
 Apache Beam de A à Z Apache Beam de A à Z
Apache Beam de A à Z
 

More from MongoDB

More from MongoDB (20)

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

Recently uploaded

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Recently uploaded (20)

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 

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

  • 1. Introduction to the 10gen C# DriverStarts at 12:30pm EST
  • 2. MongoDB C# Driver New 10gen supported driver Robert Stam Lead Engineer C# Driver
  • 3. Highlights Full featured High performance Rapidly tracks new releases of MongoDB Fully supported by 10gen
  • 4. Release Timeline v0.5 released October 15, 2010 v0.7 released November 3, 2010 v0.9 releasing soon v1.0 releasing within 1-2 months
  • 5. Downloading Binaries: http://github.com/mongodb/mongo-csharp-driver/downloads In .zip and .msi formats Source code: http://github.com/mongodb/mongo-csharp-driver Documentation: http://www.mongodb.org/display/DOCS/Drivers
  • 6. Adding References Add References to: MongoDB.Bson.dll MongoDB.Driver.dll From where? C:rogram Files (x86)ongoDB.. …ongo-csharp-driverriverinebug
  • 7. Namespaces using MongoDB.Bson; using MongoDB.Driver; // sometimes using MongoDB.Bson.IO; using MongoDB.Bson.Serialization; using MongoDB.Bson.DefaultSerializer; using MongoDB.Driver.Builders;
  • 8. BSON Document A MongoDB database holds collections of BSON documents A BSON document is a collection of elements A BSON element has: a name a type a value
  • 9. BSON Object Model A set of classes that represent a BSON document in memory Important classes: BsonDocument BsonElement BsonValue (and its subclasses) BsonType (an enum)
  • 10. BsonValue subclasses One subclass for each BsonType Examples: BsonInt32/BsonInt64 BsonString BsonDateTime BsonArray BsonDocument (embedded document) and more…
  • 11. Sample BsonDocument // using functional construction var book = new BsonDocument( new BsonElement(“Author”, “Ernest Hemingway”), new BsonElement(“Title”, “For Whom the Bell Tolls”) );
  • 12. Sample BsonDocument (continued) // using collection initializer syntax var book = new BsonDocument { { “Author”, “Ernest Hemingway” }, { “Title”, “For Whom the Bell Tolls” } }; // compiler converts that to var book = new BsonDocument(); book.Add(“Author”, “Ernest Hemingway”); book.Add(“Title”, “For Whom the Bell Tolls”);
  • 13. Sample BsonDocument (continued) // using fluent interface var book = new BsonDocument() .Add(“Author”, “Ernest Hemingway”) .Add(“Title”, “For Whom the Bell Tolls”);
  • 14. Accessing BSON Document Elements BsonValue 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 Classes Main classes: MongoServer MongoDatabase MongoCollection MongoCursor These top level classes are all thread safe. (MongoCursor is thread safe once frozen).
  • 16. MongoServer var server = MongoServer.Create(); // or var 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://server1 mongodb://server1:27018 mongodb://username:password@server1/employees mongodb://server1,server2,server3 mongodb://server1,server2,server3/?slaveok=true mongodb://localhost/?safe=true
  • 18. /?options connect=direct|replicaset replicaset=name (implies connect=replicaset) slaveok=true|false safe=true|false w=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 Modes Direct If multiple host names are provided they are tried in sequence until a match is found Replica set Multiple 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. slaveok If connect=direct If 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=replicaset If slaveok=true then all writes are sent to the primary and reads are distributed round-robin to the secondaries
  • 21. Connection Pools The driver maintains one connection pool for each server it is connected to The connections are shared among all threads A 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. MongoDatabase MongoDatabase test = server["test"]; // or MongoCredentials credentials = new MongoCredentials(username, password); MongoDatabase test = server["test", credentials]; // or MongoDatabase 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. MongoCollection MongoCollection<BsonDocument> books = test["books"]; MongoCollection<BsonDocument> books = test.GetCollection("books"); // or MongoCollection<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. Insert var 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 properties var 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. FindOne var 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 BsonDocument or var 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 query var query = Query.And( Query.EQ(“Author”, “Ernest Hemingway”), Query.GTE(“PublicationYear”, 1950) );
  • 31. Cursor options A 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 in cursor.SetSkip(100).SetLimit(10)) { // process 10 books (first 100 skipped) } // or even shorter var query = Query.GTE(“PublicationYear”, 1950); foreach (var book in books.Find(query).SetSkip(100).SetLimit(10)) { // process 10 books (first 100 skipped) }
  • 33. Update var 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. Save If it’s a new document calls Insert otherwise calls Update var 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. Remove var query = Query.EQ(“Author”, “Ernest Hemingway”); SafeModeResult result = books.Remove(query); // also books.RemoveAll(); books.Drop();
  • 37. RequestStart/RequestDone When a sequence of operations all need to occur on the same connection wrap the operations with calls to RequestStart/RequestDone RequestStart is per thread For the duration of the Request the thread holds and uses a single connection, which is not returned to the pool until RequestDone is called Calls to RequestStart can be nested. The request ends when the nesting level reaches zero again.
  • 38. RequestStart (continued) RequestStart and the using statement Return value of RequestStart is a helper object that implements IDisposable RequestDone is called for you automatically when the using statement terminates using (server.RequestStart(database)) { // a series of related operations }
  • 39. RunCommand Wrapper methods are provided for many commands, but you can always run them yourself var command = new BsonDocument(“collstats”, “books”); CommandResult result = database.RunCommand(command); CommandResult result = server.RunAdminCommand(“buildinfo”);
  • 40. Sample Command Wrappers CreateCollection DropCollection Eval GetStats Validate
  • 41. More MongoCollection Methods Count CreateIndex/EnsureIndex/DropIndex Distinct FindAndModify/FindAndRemove GeoNear Group MapReduce
  • 42. SafeMode Write operations can be followed by a call to GetLastError to verify that they succeeded SafeMode examples: SafeMode.False SafeMode.True SafeMode.W2 new SafeMode(3, TimeSpan.FromSeconds(1))
  • 43. SafeMode at different levels SafeMode options can be set at MongoServer MongoDatabase MongoCollection Individual operation SafeMode options are set at the time the instance is created (required for thread safety)
  • 44. Serialization C# classes are mapped to BSON documents AutoMap: Public fields and properties Lots of ways to customize serialization IBsonSerializable IBsonSerializer (call BsonSerializer.RegisterSerializer) Replace one or more default conventions [Bson…] Attributes (like DataContract) BsonClassMap.RegisterClassMap
  • 45. GridFS MongoDB’s Grid file system var gridFS = database.GridFS; var fileInfo = gridFS.Upload(“filename”); gridFS.Download(“filename”); // or var fileInfo = gridFS.Upload(stream, “remotename”); gridFS.Download(stream, “remotename”);
  • 46. GridFS Streams Allow you to treat files stored in GridFS as if they were local files var gridFS = database.GridFS; var stream = gridFS.Create(“remotename”); // stream implements .NET’s Stream API // more examples var stream = gridFS.OpenRead(“remotename”); var stream = gridFS.Open(“remotename”, FileMode.Append);
  • 47. Presentation Available Online Slides available at: http://www.slideshare.net/mongodb Webinar available at: http://www.10gen.com/webinars/csharp