Webinar: Building Your First Application with MongoDB


Published on

This webinar will introduce the features of MongoDB by walking through how one can building a simple location-based checkin application using MongoDB. The talk will cover the basics of MongoDB's document model, query language, map-reduce framework and deployment architecture.

  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • AGPL – GNU Affero General Public License
  • 10gen Drivers
  • Plus community drivers.
  • "50804d0bd94ccab2da652599" is a 24 byte string (12 byte ObjectId hex encoded).
  • Webinar: Building Your First Application with MongoDB

    1. 1. Building your First App withMongoDBBlossom CoryatSolutions Architect, 10gen
    2. 2. Today‟s Talk• Introduction to MongoDB• Discuss data modeling, queries, indexes, updates and aggregation in MongoDB within the context of building a location-based app
    3. 3. What is MongoDB?
    4. 4. MongoDB is a ___________database• Document Oriented• Open source• High performance• Highly Available• Horizontally scalable• Full featured
    5. 5. Document Oriented• A document is essentially an associative array• Document == JSON object• Document == PHP Array• Document == Python Dict• Document == Ruby Hash• Etc.
    6. 6. Open Source• MongoDB is an open source project – Started and maintained by 10gen• Licensed under the AGPL• Commercial licenses available• On GitHub• Contributions welcome
    7. 7. High Performance• Written in C++• Runs nearly everywhere• Extensive use of memory-mapped files• Data serialized as BSON (fast parsing)• Full support for primary & secondary indexes• Document model = less work
    8. 8. Full Featured• Ad Hoc queries• Real time aggregation• Rich query capabilities• Flexible schema• Geospatial features• Support for most programming languages
    9. 9. MongoDB drivers• Official Support for 12 languages• Community drivers for tons more• Drivers connect to mongo servers• Drivers translate BSON into native types• Installed using typical means (npm, pecl, gem, pip)
    10. 10. Highly Available
    11. 11. Replica Sets• Redundancy and Failover• Multi-DC deployments• Zero downtime for upgrades and maintenance
    12. 12. Horizontally Scalable
    13. 13. Sharding• Partition your data• Auto-balancing• Scale write throughput• Increase capacity
    14. 14. Document Database
    15. 15. RDBMS MongoDBRow ➜ DocumentTable, View ➜ CollectionIndex ➜ IndexJoin ➜ Embedded DocumentForeign ➜ ReferenceKeyPartition ➜ ShardTerminology
    16. 16. Typical (relational) ERD
    17. 17. MongoDB ERD
    18. 18. Example Document{ _id : ObjectId("4c4ba5c0672c685e5e8aabf3"), author : "Blossom", date : ISODate("2012-11-02T11:52:27.442Z"), title: "Intro to MongoDB", tags : [ "tech", "databases”, ”documents" ], comments : [{ author : "Fred", date : ISODate("2012-11-03T17:22:21.124Z"), text : ”interesting article, lots of great nuggets of wisdom" }], comment_count : 1 }
    19. 19. Building a check-in webapp
    20. 20. Requirements• Users should be able to check in to a location• Should be able to view check-ins by location• Ability to assign categories to places• Find nearby places• Generate check-in statistics
    21. 21. First step in any application isDetermine your entities
    22. 22. Check-in App Entities• People checking in• Places to check in to• Check-in events
    23. 23. In a relational based appWe would start by doingschema design
    24. 24. Relational schema design• Large entity relationship diagrams• Complex create table statements• Tables just to join tables together• ORMs to map tables to objects• Lots of revisions until we get it just right
    25. 25. In a MongoDB based appWe start building ourand let the schema evolveapp
    26. 26. MongoDB collections• Users• Places• Check-ins – Separate collection to manage discrete check-in events and support high workload of writes
    27. 27. We‟ll use the JS shell to getstarted
    28. 28. Start with an object(or array, hash, dict, etc)> user = { firstname: fred, lastname: jones,}
    29. 29. Insert the record> db.users.insert(user) No collection creation needed
    30. 30. Querying for the user> db.users.findOne(){ "_id" : ObjectId("50804d0bd94ccab2da652599"), "firstname" : "fred", "lastname" : "jones"}
    31. 31. _id• _id is the primary key in MongoDB• Automatically indexed• Automatically created as an ObjectId if not provided• Any unique immutable value could be used
    32. 32. ObjectId• ObjectId is a special 12 byte value• Guaranteed to be unique across your cluster• ObjectId("50804d0bd94ccab2da652599") |---------||-----||-----||--------| ts mac pid inc
    33. 33. Places v1> db.places.insert({ name: “Exploratorium”, address: “3601 Lyon St” city: “San Francisco”, postcode: 94123}
    34. 34. Places v1> db.places.insert({ name: “Exploratorium”, address: “3601 Lyon St” city: “San Francisco”, postcode: 94123}> db.places.find({name:”Exploratorium”})
    35. 35. Places v2> db.places.insert({ name: “Exploratorium”, address: “3601 Lyon St” city: “San Francisco”, postcode: 94123, categories: [“Social”, “Arts”, “Museums”]}
    36. 36. Places v2> db.places.insert({ name: “Exploratorium”, address: “3601 Lyon St” city: “San Francisco”, postcode: 94123, categories: [“Social”, “Arts”, “Museums”]}> db.places.ensureIndex({categories: 1})> db.places.find({categories: ”Social”})
    37. 37. Places v3> db.places.insert({ name: “Exploratorium”, address: “3601 Lyon St” city: “San Francisco”, postcode: 94123, categories: [“Social”, “Arts”, “Museums”], location: [37.803963,-122.448531]}> db.places.ensureIndex({location: “2d”})> db.places.find({location:{$near:[37.81,-122.45]}})
    38. 38. Indexes• Can be created on any field – Including fields within sub-documents or embedded arrays• Support for compound indexes on any combination of keys• Indexes should exist for primary, common, and user-facing queries
    39. 39. Indexes on Places// creating indexes> db.places.ensureIndex({name:1})> db.places.ensureIndex({categories:1})> db.places.ensureIndex({location:”2d”})// finding by regular expression> db.places.find({name:/^explor/i})// finding nearby> db.places.find({location:{$near:[37.81,-122.45]}})// finding by category> db.places.find({categories: ”Social”})
    40. 40. Updating Documents• MongoDB supports atomic, in-place document updates• $inc• $set, $unset• $push, $pushAll• $addToSet, $each• $pop, $pull, $pullAll• $rename• $bit
    41. 41. Updating> db.checkins.insert({ place_id: pid, user_id: uid, datetime: new Date()})// update the “checkins” count on place and user// “checkins” will be added if it doesn‟t exist> db.places.update({_id: pid}, {$inc: {checkins: 1}})> db.users.update({_id: uid}, {$inc: {checkins: 1}})
    42. 42. Simple Statistics// find the last 10 checkins for a place:> p = db.places.find({name:”Exploratorium”})> db.checkins.find({place_id:p[„_id‟]}) .sort({datetime:-1}).limit(10)// how many people checked in today> db.checkins.find({place_id:p[„_id‟], datetime: {$gt: midnight}}).count()
    43. 43. Aggregation Framework• Documents pass through a pipeline of operations• Mechanism to calculate aggregate values across your data• Similar functionality to GROUP BY and related SQL operators• Along with computation, data can be reshaped – Add computed fields – Create virtual sub-objects – Extract sub-fields
    44. 44. Aggregation FrameworkOperators• $project• $match• $limit• $skip• $unwind• $group• $sort
    45. 45. Advanced Statistics// checkins per place per day of the week> db.checkins.aggregate( {$project: { place_id:1, dotw: { $dayOfWeek: ”$datetime”} }}, {$group: { _id: {place_id: “$place_id”, dotw: “$dotw”}, count: {$sum: 1} }})
    46. 46. Deployment
    47. 47. Deployment• Single server - need a strong backup plan P
    48. 48. Deployment• Single server - need a strong backup plan P• Replica sets P S S - High availability - Automatic failover
    49. 49. Deployment• Single server - need a strong backup plan P• Replica sets P S S - High availability - Automatic failover P S S• Sharded - Horizontally scale - Auto balancing P S S
    50. 50. Learn More:10gen.com/presentationseducation.10gen.com