NDC London 2013 - Mongo db for c# developers

56
MongoDB for C# Developers Simon Elliston Ball Head of Big Data @sireb

description

How and when to use document databases, how MongoDB compares to Raven and Couchbase, and an intro to the Mongo Driver to C#.

Transcript of NDC London 2013 - Mongo db for c# developers

Page 1: NDC London 2013 - Mongo db for c# developers

MongoDB for C# DevelopersSimon Elliston Ball Head of Big Data !

@sireb !

!

!

!

Page 2: NDC London 2013 - Mongo db for c# developers

http://www.mongodb.org/

Page 3: NDC London 2013 - Mongo db for c# developers

Document Database

Page 4: NDC London 2013 - Mongo db for c# developers

Document Databaseid full_name address1 John Smith 3a Test Street2 Jane Doe 1b Fake Street3 ... ...

Page 5: NDC London 2013 - Mongo db for c# developers

id customer_id

order_date1 1 ... 2013-10-1

02 1 ... ...3 ... ... ...

Document Databaseid full_name address1 John Smith 3a Test Street2 Jane Doe 1b Fake Street3 ... ...

Page 6: NDC London 2013 - Mongo db for c# developers

id customer_id

order_date1 1 ... 2013-10-1

02 1 ... ...3 ... ... ...

Document Databaseid full_name address1 John Smith 3a Test Street2 Jane Doe 1b Fake Street3 ... ...id order_id product_id

1 1 1032 1 ...3 ... ...

Page 7: NDC London 2013 - Mongo db for c# developers

id customer_id

order_date1 1 ... 2013-10-1

02 1 ... ...3 ... ... ...

Document Databaseid full_name address1 John Smith 3a Test Street2 Jane Doe 1b Fake Street3 ... ...id customer_id order_date

1 1 2013-10-102 1 ...3 ... ...

Page 8: NDC London 2013 - Mongo db for c# developers

id customer_id

order_date1 1 ... 2013-10-1

02 1 ... ...3 ... ... ...

Document Databaseid full_name address1 John Smith 3a Test Street2 Jane Doe 1b Fake Street3 ... ...id customer_id order_date

1 1 2013-10-102 1 ...3 ... ...

customers = [ { "_id" : ObjectId("5256b399ac46b80084974d9a"), "name" : "John Smith", "address" : "3a Test Street", "orders" [ { "order_date": "2013-10-10", "order_item": [ { "product": "Widget"...} ... ] ... }] }, { "_id" : ObjectId("5256b3a8ac46b80084974d9b"), "name" : "Jane Doe", "address" : "1b Fake Street" } ]

Page 9: NDC London 2013 - Mongo db for c# developers

Key -> JSON

Page 10: NDC London 2013 - Mongo db for c# developers

Document Database - Why?Flexible Data Model

Rapid Development

Scalability

- No Schema

Page 11: NDC London 2013 - Mongo db for c# developers

Document Database - When?Blogs

Page 12: NDC London 2013 - Mongo db for c# developers

Document Database - When?Content management

When read patterns are fixed

Scaling requirements are unknown

When write speed matters

Page 13: NDC London 2013 - Mongo db for c# developers
Page 14: NDC London 2013 - Mongo db for c# developers
Page 15: NDC London 2013 - Mongo db for c# developers
Page 16: NDC London 2013 - Mongo db for c# developers

• Transactions per document

• Master-slave replication

• Many many languages: C#,

JavaScript, Java, PHP, Python, Ruby, Scala, Erlang, Go, C, C++, Perl (and those are just the official ones)

• ACID, multi-document

• But… Background Indexing

• Master-master replication

• .NET Only

Page 17: NDC London 2013 - Mongo db for c# developers

• Main interface: CLI

• Transactions per document

• Master-slave replication

• Many many languages: C#,

JavaScript, Java, PHP, Python, Ruby, Scala, Erlang, Go, C, C++, Perl (and those are just the official ones)

• GUI Client

• Native JSON

• Geo-aware replication

• REST Interface, so anything

• View based queries

Page 18: NDC London 2013 - Mongo db for c# developers

Getting started with MongoDB

Download from http://www.mongodb.org/

Page 19: NDC London 2013 - Mongo db for c# developers
Page 20: NDC London 2013 - Mongo db for c# developers

Getting started with the C# client

PM> Install-Package mongocsharpdriver

Page 21: NDC London 2013 - Mongo db for c# developers
Page 22: NDC London 2013 - Mongo db for c# developers

Wooah there. I thought you said JSON...

Page 23: NDC London 2013 - Mongo db for c# developers

BSON Binary JSON

Page 24: NDC London 2013 - Mongo db for c# developers

BSON Binary JSONTyped

Page 25: NDC London 2013 - Mongo db for c# developers

BSON Binary JSONTyped

Serialisation library

Page 26: NDC London 2013 - Mongo db for c# developers

BSON Binary JSONTyped

Serialisation library

Annotate POCOs to control mapping or write config code if you must

Page 27: NDC London 2013 - Mongo db for c# developers

Connecting...var connectionString = "mongodb://localhost"; var client = new MongoClient(connectionString); var server = client.GetServer();

Page 28: NDC London 2013 - Mongo db for c# developers

Connecting...

That’s it. The driver will disconnect, release objects and pool for you. !

But...

var connectionString = "mongodb://localhost"; var client = new MongoClient(connectionString); var server = client.GetServer();

Page 29: NDC London 2013 - Mongo db for c# developers

CollectionsDatabase

Collection

Document

_id

field…

Page 30: NDC London 2013 - Mongo db for c# developers

CRUD creating new documents

var developerCollection = database.GetCollection<Developer>("team"); !var Developer = new Developer(1,"Test", "Person"); developerCollection.Insert(Developer); var Developer2 = new Developer(2,"Another", "Developer"); developerCollection.Insert(Developer2)

var documentCollection = database.GetCollection("team"); !BsonDocument document = new BsonDocument(); document.Add(new BsonElement("name", "Testing")) .Add(new BsonElement("number", new BsonInt32(42))); !documentCollection.Insert(document);

The BsonDocument way:

With mapped entities:

Page 31: NDC London 2013 - Mongo db for c# developers

CRUD creating new documents

var documentCollection = database.GetCollection("team"); !BsonDocument document = new BsonDocument(); document.Add(new BsonElement("name", "Testing")) .Add(new BsonElement("number", new BsonInt32(42))); !documentCollection.Insert(document);

The BsonDocument way:

Beware of mixing your BSONsList<Developer> allDevelopers = developerResults.ToList<Developer>();

Page 32: NDC London 2013 - Mongo db for c# developers

CRUD creating new documentsBeware of mixing your BSONsList<Developer> allDevelopers = developerResults.ToList<Developer>();

Page 33: NDC London 2013 - Mongo db for c# developers

CRUD basic document readsMongoCursor<BsonDocument> documentResults = documentCollection.FindAll(); MongoCursor<Developer> developerResults = developerCollection.FindAll();

Page 34: NDC London 2013 - Mongo db for c# developers

CRUD basic document readsMongoCursor<BsonDocument> documentResults = documentCollection.FindAll(); MongoCursor<Developer> developerResults = developerCollection.FindAll();

var cursor = collection.FindAll(); cursor.Skip = 100; cursor.Limit = 10; !foreach (var developer in cursor) { ...

Page 35: NDC London 2013 - Mongo db for c# developers

CRUD basic document readsMongoCursor<BsonDocument> documentResults = documentCollection.FindAll(); MongoCursor<Developer> developerResults = developerCollection.FindAll();

var readQuery = Query<Developer>.EQ(n => n.PersonId, 2); Developer developerRead = developerCollection.FindOne(readQuery);

var cursor = collection.FindAll(); cursor.Skip = 100; cursor.Limit = 10; !foreach (var developer in cursor) { ... }

Page 36: NDC London 2013 - Mongo db for c# developers

CRUD basic document readsMongoCursor<BsonDocument> documentResults = documentCollection.FindAll(); MongoCursor<Developer> developerResults = developerCollection.FindAll();

var readQuery = Query<Developer>.EQ(n => n.PersonId, 2); Developer developerRead = developerCollection.FindOne(readQuery);

BsonDocument documentRead = documentCollection.FindOne(new QueryDocument { { "_id", documentId } });

var cursor = collection.FindAll(); cursor.Skip = 100; cursor.Limit = 10; !foreach (var developer in cursor) { ... }

Page 37: NDC London 2013 - Mongo db for c# developers

CRUD updatedeveloperRead.LastName = "Something-Else"; developerCollection.Save(developerRead);

Page 38: NDC London 2013 - Mongo db for c# developers

CRUD updateWrite Concerns

Only relevant with ReplicationThe number of replicas which need to report successful writes

collection.Save(developerRead, new MongoInsertOptions { WriteConcern = WriteConcern.WMajority } );

Page 39: NDC London 2013 - Mongo db for c# developers

CRUD updatevar update = new UpdateDocument { { "$set", new BsonDocument("LastName", "A new name") } }; !var query = new QueryDocument { { "LastName", "Developer" } }; !collection.Update(query, update);

NB. Only updates one document

Page 40: NDC London 2013 - Mongo db for c# developers

CRUD updatevar update = new UpdateDocument { { "$set", new BsonDocument("LastName", "A new name") } }; !var query = new QueryDocument { { "LastName", "Developer" } }; !collection.Update(query, update);

NB. Only updates one document

collection.Update(query, update, new MongoUpdateOptions { Flags = UpdateFlags.Multi });

Applies to all documents that match query

Page 41: NDC London 2013 - Mongo db for c# developers

CRUD upsertvar update = new UpdateDocument { { "$set", new BsonDocument("LastName", "A new name") } }; var query = Query<Developer>.EQ(d => d.PersonId, 10); !collection.Update(query, update, new MongoUpdateOptions { Flags = UpdateFlags.Upsert });

Page 42: NDC London 2013 - Mongo db for c# developers

CRUD deletingvar query = new QueryDocument { { "LastName", "Person" } }; collection.Remove(query);

Page 43: NDC London 2013 - Mongo db for c# developers

CRUD deletingvar query = new QueryDocument { { "LastName", "Person" } }; collection.Remove(query);

collection.RemoveAll();

collection.Drop();

Page 44: NDC London 2013 - Mongo db for c# developers

LINQ integrationJust make the collection queryableusing System.Linq; using MongoDB.Driver.Linq; !var query = from e in collection.AsQueryable() where e.LastName == "Person" select e; !foreach (var developer in query){ ...

Page 45: NDC London 2013 - Mongo db for c# developers

GridFS in C#16MB document limitGridFS used to break documents into chunksusing (var fs = new FileStream("largeVideo.m4v", FileMode.Open)) { database.GridFS.Upload(fs, "largeVideo.m4v"); }

database.GridFS.Download("test.m4v", "largeVideo.m4v");

Page 46: NDC London 2013 - Mongo db for c# developers

MapReduce (JavaScript)var map = "function() {" + " for (var key in this) {" + " emit(key, { count : 1 });" + " }" + "}"; !var reduce = "function(key, emits) {" + " total = 0;" + " for (var i in emits) {" + " total += emits[i].count;" + " }" + " return { count : total };" + "}"; !var mr = collection.MapReduce(map, reduce);

Yes, it’s a word count. Yes, it’s JavaScript.

Page 47: NDC London 2013 - Mongo db for c# developers

Special Queries GeoNearvar query = Query.EQ("properties.amenity", new BsonString("pub")); // here double lon = 54.9117468; double lat = -1.3737675; !var earthRadius = 6378.0; // km var rangeInKm = 3000.0; // km !var options = GeoNearOptions .SetMaxDistance(rangeInKm / earthRadius /* to radians */) .SetSpherical(true); !var results = collection.GeoNear(query, lat, lon, 10, options); !foreach (var result in results.Hits) ...

Page 48: NDC London 2013 - Mongo db for c# developers

Aggregation Framework

Page 49: NDC London 2013 - Mongo db for c# developers

Aggregation FrameworkPipeline based

Page 50: NDC London 2013 - Mongo db for c# developers

Aggregation FrameworkPipeline basedChained operators

Page 51: NDC London 2013 - Mongo db for c# developers

Aggregation FrameworkPipeline basedChained operators

$project $match $limit $skip $unwind $group $sort … http://docs.mongodb.org/manual/reference/operator/aggregation/

Page 52: NDC London 2013 - Mongo db for c# developers

Aggregation FrameworkDemo

Page 53: NDC London 2013 - Mongo db for c# developers

SummaryDocument databases are simple BSON annotation makes POCO mapping is easy CRUD is straight forward You can use LINQ Hard stuff is possible

Page 54: NDC London 2013 - Mongo db for c# developers

Acknowledgements

MongoDB, Mongo, and the leaf logo are registered trademarks of MongoDB, Inc.

Page 55: NDC London 2013 - Mongo db for c# developers

ResourcesThe MongoDB C Sharp Language Center:http://docs.mongodb.org/ecosystem/drivers/csharp/A tutorial on the driver from MongoDB themselves:http://docs.mongodb.org/ecosystem/tutorial/use-csharp-driver/#csharp-driver-tutorialSample code from this talk:https://github.com/simonellistonball/MongoForCsharpSamplesA good walkthrough on MongoDB with ASP.NET MVC:http://www.drdobbs.com/database/mongodb-with-c-deep-dive/240152181

Bonus extras A Glimpse plugin to view mongo query details:https://github.com/simonellistonball/Glimpse.MongoDB

Page 56: NDC London 2013 - Mongo db for c# developers

Questions?Simon Elliston Ball [email protected] !

@sireb !

!

!

http://bit.ly/MongoForCsharp