introduction to the new official c# driver developed by 10gen

47
Introduction to the 10gen C# Driver Starts at 12:30pm EST

Upload: mongodb

Post on 15-Jan-2015

6.696 views

Category:

Technology


3 download

DESCRIPTION

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

TRANSCRIPT

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

Introduction to the 10gen C# Driver

Starts at 12:30pm EST

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

MongoDB C# Driver

New 10gen supported driverRobert Stam

Lead Engineer C# Driver

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

Highlights

• Full featured• High performance• Rapidly tracks new releases of MongoDB• Fully supported by 10gen

Page 4: Introduction to the new official C# Driver developed 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

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

Downloading

Binaries:http://github.com/mongodb/mongo-csharp-driver/downloads

In .zip and .msi formatsSource code:http://github.com/mongodb/mongo-csharp-driver

Documentation:http://www.mongodb.org/display/DOCS/Drivers

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

Adding References

• Add References to:– MongoDB.Bson.dll– MongoDB.Driver.dll

• From where?– C:\Program Files (x86)\MongoDB\...– …\mongo-csharp-driver\Driver\bin\Debug

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

Namespacesusing MongoDB.Bson;using MongoDB.Driver;

// sometimesusing MongoDB.Bson.IO;using MongoDB.Bson.Serialization;using MongoDB.Bson.DefaultSerializer;using MongoDB.Driver.Builders;

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

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

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

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)

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

BsonValue subclasses

• One subclass for each BsonType• Examples:– BsonInt32/BsonInt64– BsonString– BsonDateTime– BsonArray– BsonDocument (embedded document)– and more…

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

Sample BsonDocument// using functional constructionvar book = new BsonDocument( new BsonElement(“Author”, “Ernest Hemingway”), new BsonElement(“Title”,

“For Whom the Bell Tolls”));

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

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”);

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

Sample BsonDocument (continued)// using fluent interfacevar book = new BsonDocument() .Add(“Author”, “Ernest Hemingway”) .Add(“Title”, “For Whom the Bell Tolls”);

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

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;bool outOfPrint = book[“OutOfPrint”].AsBoolean;bool outOfPrint = book[“OutOfPrint”].ToBoolean();

BsonElement element = document.GetElement(“name”);

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

C# Driver Classes

• Main classes:– MongoServer– MongoDatabase– MongoCollection– MongoCursor

These top level classes are all thread safe.(MongoCursor is thread safe once frozen).

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

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.

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

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

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

/?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

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

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.

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

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

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

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)

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

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.

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

MongoCollectionMongoCollection<BsonDocument> books = test["books"];MongoCollection<BsonDocument> books = test.GetCollection("books");

// or

MongoCollection<Book> books = test.GetCollection<Book>("books");

Book is default document type

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

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.

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

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.

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

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).

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

FindOnevar books = database[“books”];var book = books.FindOne(); // returns BsonDocument

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

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

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

Find (with query)var query = new BsonDocument { { “Author”, “Ernest Hemingway” }};var cursor = books.Find(query);foreach (var book in cursor) { // process book}

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

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));

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

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)}

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

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 shortervar query = Query.GTE(“PublicationYear”, 1950);foreach (var book in books.Find(query).SetSkip(100).SetLimit(10)) { // process 10 books (first 100 skipped)}

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

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);

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

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);

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

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).

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

Removevar query = Query.EQ(“Author”, “Ernest Hemingway”);SafeModeResult result = books.Remove(query);

// also

books.RemoveAll();books.Drop();

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

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.

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

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 }

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

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”);

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

Sample Command Wrappers

• CreateCollection• DropCollection• Eval• GetStats• Validate

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

More MongoCollection Methods

• Count• CreateIndex/EnsureIndex/DropIndex• Distinct• FindAndModify/FindAndRemove• GeoNear• Group• MapReduce

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

SafeMode

• Write operations can be followed by a call to GetLastError to verify that they succeeded

• SafeMode examples:

SafeMode.FalseSafeMode.TrueSafeMode.W2new SafeMode(3, TimeSpan.FromSeconds(1))

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

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)

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

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

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

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”);

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

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 examplesvar stream = gridFS.OpenRead(“remotename”);var stream = gridFS.Open(“remotename”, FileMode.Append);

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

Presentation Available Online

• Slides available at:

http://www.slideshare.net/mongodb

• Webinar available at:

http://www.10gen.com/webinars/csharp