Introduction to the 10gen C# DriverStarts at 12:30pm EST<br />
MongoDB C# Driver<br />New 10gen supported driver<br />Robert Stam<br />Lead Engineer C# Driver<br />
Highlights<br />Full featured<br />High performance<br />Rapidly tracks new releases of MongoDB<br />Fully supported by 10...
Release Timeline<br />v0.5 released October 15, 2010<br />v0.7 released November 3, 2010<br />v0.9 releasing soon<br />v1....
Downloading<br />Binaries:<br />http://github.com/mongodb/mongo-csharp-driver/downloads<br />In .zip and .msi formats<br /...
Adding References<br />Add References to:<br />MongoDB.Bson.dll<br />MongoDB.Driver.dll<br />From where?<br />C:Program Fi...
Namespaces<br />using MongoDB.Bson;<br />using MongoDB.Driver;<br />// sometimes<br />using MongoDB.Bson.IO;<br />using Mo...
BSON Document<br />A MongoDB database holds collections of BSON documents<br />A BSON document is a collection of elements...
BSON Object Model<br />A set of classes that represent a BSON document in memory<br />Important classes:<br />BsonDocument...
BsonValue subclasses<br />One subclass for each BsonType<br />Examples:<br />BsonInt32/BsonInt64<br />BsonString<br />Bson...
Sample BsonDocument<br />// using functional construction<br />var book = new BsonDocument(<br />    new BsonElement(“Auth...
Sample BsonDocument (continued)<br />// using collection initializer syntax<br />var book = new BsonDocument {<br />    { ...
Sample BsonDocument (continued)<br />// using fluent interface<br />var book = new BsonDocument()<br />    .Add(“Author”, ...
Accessing BSON Document Elements<br />BsonValue value = document[“name”];<br />string author = book[“Author”].AsString;<br...
C# Driver Classes<br />Main classes:<br />MongoServer<br />MongoDatabase<br />MongoCollection<br />MongoCursor<br />These ...
MongoServer<br />var server = MongoServer.Create();<br />// or<br />var url = “mongodb://localhost:27017”;<br />var server...
Connection Strings (URLs)<br />Connection string format:<br />mongodb://[credentials@]hosts[/[database][?options]]<br />Ex...
/?options<br />connect=direct|replicaset<br />replicaset=name (implies connect=replicaset)<br />slaveok=true|false<br />sa...
Connection Modes<br />Direct<br />If multiple host names are provided they are tried in sequence until a match is found<br...
slaveok<br />If connect=direct<br />If slaveok=true then it is OK if the server is not a primary (useful to connect direct...
Connection Pools<br />The driver maintains one connection pool for each server it is connected to<br />The connections are...
MongoDatabase<br />MongoDatabase test = server["test"];<br />// or<br />MongoCredentials credentials =<br />	new MongoCred...
MongoCollection<br />MongoCollection<BsonDocument> books = test["books"];<br />MongoCollection<BsonDocument> books =<br />...
MongoCollection (continued)<br />var books = database[“books”, SafeMode.True];<br />var books = database.GetCollection<Boo...
Insert<br />var books = database[“books”];<br />var book = new BsonDocument {<br />    { “Author”, “Ernest Hemingway” },<b...
Insert (using serialization)<br />// Book is a class with Author and Title properties<br />var books = database.GetCollect...
FindOne<br />var books = database[“books”];<br />var book = books.FindOne(); // returns BsonDocument<br />
FindOne (using serialization)<br />var books = database[“books”];<br />var book = books.FindOneAs<Book>();<br />    // ret...
Find (with query)<br />var query = new BsonDocument {<br />    { “Author”, “Ernest Hemingway” }<br />};<br />var cursor = ...
Find (with Query builder)<br />var query = Query.EQ(“Author”, “Ernest Hemingway”);<br />var cursor = books.Find(query);<br...
Cursor options<br />A cursor can be modified before being enumerated (before it is frozen)<br />var query = Query.GTE(“Pub...
Cursor options (fluent interface)<br />var query = Query.GTE(“PublicationYear”, 1950);<br />var cursor = books.Find(query)...
Update<br />var query = Query.EQ(“Title”, “For Who”);<br />var update = new BsonDocument {<br />    { “$set”, new BsonDocu...
Update (using Update builder)<br />var query = Query.EQ(“Title”, “For Who”);<br />var update =<br />Update.Set(“Title”, “F...
Save<br />If it’s a new document calls Insert otherwise calls Update<br />var query = Query.EQ(“Title”, “For Who”);<br />v...
Remove<br />var query = Query.EQ(“Author”, “Ernest Hemingway”);<br />SafeModeResult result = books.Remove(query);<br />// ...
RequestStart/RequestDone<br />When a sequence of operations all need to occur on the same connection wrap the operations w...
RequestStart (continued)<br />RequestStart and the using statement<br />Return value of RequestStart is a helper object th...
RunCommand<br />Wrapper methods are provided for many commands, but you can always run them yourself<br />var command =<br...
Sample Command Wrappers<br />CreateCollection<br />DropCollection<br />Eval<br />GetStats<br />Validate<br />
More MongoCollection Methods<br />Count<br />CreateIndex/EnsureIndex/DropIndex<br />Distinct<br />FindAndModify/FindAndRem...
SafeMode<br />Write operations can be followed by a call to GetLastError to verify that they succeeded<br />SafeMode examp...
SafeMode at different levels<br />SafeMode options can be set at<br />MongoServer<br />MongoDatabase<br />MongoCollection<...
Serialization<br />C# classes are mapped to BSON documents<br />AutoMap:<br />Public fields and properties<br />Lots of wa...
GridFS<br />MongoDB’s Grid file system<br />var gridFS = database.GridFS;<br />var fileInfo = gridFS.Upload(“filename”);<b...
GridFS Streams<br />Allow you to treat files stored in GridFS as if they were local files<br />var gridFS = database.GridF...
Presentation Available Online<br />Slides available at:<br />http://www.slideshare.net/mongodb<br />Webinar available at:<...
Upcoming SlideShare
Loading in...5
×

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

7,188

Published on

Slides from Robert Stam's 12/1 presentation on the C# driver for MongoDB

Published in: Technology, Education
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
7,188
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
103
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

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

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

    Clipping is a handy way to collect important slides you want to go back to later.

×