MongoDB- Crud Operation


Published on

Published in: Education, Technology
  • Be the first to comment

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

No notes for slide

MongoDB- Crud Operation

  1. 1. 1 ®
  2. 2. 2  Module 1  Introduction and Overview  No SQL  Module 2  CRUD Operations  CRUD Concerns  Module 3  Schema Design and Data Modeling  Comparison with Relational Systems  Module 4  Administration  Backup and Recovery  Module 5  Scalability and Availability  Replication and Sharding  Module 6  Indexing and Aggregation Frame work  Performance Tuning  Module 7  Application Engineering and Mongo DB Tools  Interface with Other Language  Module 8  Project, Additional Concepts and Cases Studies MongoDB Course Topics
  3. 3. 3 MongoDB Course Module 02 : CRUD Operations
  4. 4. 4 Topics of the Day Module 1 – Revision MongoDB Development Overview MongoDB Production Overview MongoDB CRUD Introduction MongoDB CRUD Concepts MongoDB CRUD Syntax & Queries
  5. 5. 5 Annie’s Question- Related to Module1 What are typical uses for MongoDB?
  6. 6. 6 Annie’s Answer Content management systems, Mobile applications, Gaming, E-commerce, Analytics, Archiving, Logging, Data Hub.
  7. 7. 7 Annie’s Question Where you should not use MongoDB?
  8. 8. 8 Annie’s Answer For those systems which require SQL, joins, and multi-object transactions.
  9. 9. 9 Annie’s Question Does MongoDB handle caching?
  10. 10. 10 Annie’s Answer Yes. MongoDB keeps all of the most recently used data in RAM. If you have created indexes for your queries and your working data set fits in RAM, MongoDB serves all queries from memory.
  11. 11. 11 Annie’s Question What is the difference in mongo and mongos?
  12. 12. 12 Annie’s Answer Mongo  For simple shell access Mongos  For Sharded Cluster
  13. 13. 13 mongod (Mongo Database) mongos mongos mongos app dirver app dirver app dirverapp dirver Query Sender MongoDB Development Environment
  14. 14. 14 app server app server app serverapp server Mongos Mongos Mongos Config 1 Config 2 Config 3 mongod mongod mongod Sahrd1 mongod mongod mongod Sahrd2 mongod mongod mongod Sahrd3 mongod mongod mongod Sahrd4 mongod mongod mongod Sahrd5 mongod mongod mongod Sahrd6 Query Router Read/Write Operations Mongo DB Cluster MongoDB Production Overview
  15. 15. 15 Introduction MongoDB provides rich functionalities for reading and manipulating data. CRUD stands for Create, Read, Update and Delete. These terms are the basic stuffs for all interactions with the databases. C R U D MongoDB CRUD Introduction
  16. 16. 16 CRUD C R U D Create Read Update Delete MongoDB CRUD Operations
  17. 17. 17 Data Operations Data Modification Query Database Operations Read Create Update Delete
  18. 18. 18 CRUD Concepts Read Operations Write Operations MongoDB CRUD Concepts
  19. 19. 19 Read Operations Cursors Query Optimization Query Plans Distributed Queries Read Operations
  20. 20. 20 CURSORS Queries return iterable objects, called cursors, that hold the full result set of the query request. db.collection.find() method queries a collection and returns a cursor to the returning documents. To access the documents, you need to iterate the cursor. If the returned cursor is not assigned to a variable using the var keyword, then the cursor is automatically iterated up to 20 times. > db.runCommand( { cursorInfo: 1 } ) is used to find information about cursor. CURSORS
  21. 21. 21 > db.runCommand( { cursorInfo: 1 } ) > db.runCommand<{ cursor Info : 1 } > { “ totalOpen”: 0, “ client Cursors_size”:0, “timedout”: 0, “ok” :1} > > db.runCommand( { cursorInfo: 1 } ) > db.runCommand<{ cursor Info : 1 } > { “ totalOpen”: 1, “ client Cursors_size”:1, “timedout”: 0, “ok” :1} > Cursor Information
  22. 22. 22 > Create an Index to Support Read Operations > Query Selectivity > Covering a Query > Query Plans Query Optimization
  23. 23. 23 Query Behavior All queries in MongoDB address a single collection. You can modify the query to impose limits, skips, and sort orders. The order of documents returned by a query is not defined and is not defined unless you specify a sort(). Operations that modify existing documents (i.e. updates) use the same query syntax as queries to select documents to update. MongoDB provides a db.collection.findOne() method as a special case of find() that returns a single document. In aggregation pipeline, the $match pipeline stage provides access to MongoDB queries. Query Behavior
  24. 24. 24 Annie’s Question When Query Plan Revision happens?
  25. 25. 25 Annie’s Answer • The collection receives 1,000 write operations. • The reIndex rebuilds the index. • You add or drop an index. • The mongod process restarts.
  26. 26. 26 Annie’s Question How do I isolate cursors from intervening write operations?
  27. 27. 27 Annie’s Answer MongoDB cursors can return the same document more than once in some situations. You can use the snapshot() method on a cursor to isolate the operation for a very specific case.
  28. 28. 28 Read Operations to Replica Sets Read Operations to Sharded Clusters Distributed Query Distributed Queries
  29. 29. 29 app server app server app serverapp server Mongos Mongos Mongos Config 1 Config 2 Config 3 mongod mongod mongod Sahrd1 mongod mongod mongod Sahrd2 mongod mongod mongod Sahrd3 mongod mongod mongod Sahrd4 mongod mongod mongod Sahrd5 mongod mongod mongod Sahrd6 Query Router Read/Write Operations Mongo DB Cluster Sharded Collection Read Operations to Sharded Clusters
  30. 30. 30 Sahrd1 Sahrd1 Secondary Primary Secondary Secondary Primary Secondary Config 1 Config 2 Config 3 app server MongosQuery Router Read Operations Write Operations Mongo DB Cluster Read Operations to ReplicaSet
  31. 31. 31 Write Operations Write Operations Write Concern Write Operation Performance Record Padding Distributed Write Operations Bulk Inserts in MongoDB
  32. 32. 32 With stronger write concerns, clients wait after sending a write operation for MongoDB to confirm the write operations. In some failure cases, write operations issued with weak write concerns may not persist. When inserts, updates and deletes have a weak write concern, write operations return quickly. The strength of the write concerns determine the level of guarantee. Write concern describes the guarantee that MongoDB provides when reporting on the success of a write operation.. Success Write Concerns
  33. 33. 33 Write Concern Levels Errors Ignored Unacknowledged AcknowledgedJournaled Replica Acknowledged Write Concerns Levels
  34. 34. 34  With an errors ignored write concern, MongoDB does not acknowledge write operations.  With this level of write concern, the client cannot detect failed write operations.  These errors include connection errors and mongod exceptions such as duplicate key exceptions for unique indexes.  Although the errors ignored write concern provides fast performance, this performance gain comes at the cost of significant risks for data persistence and durability.  To set errors ignored write concern, specify w values of -1 to your driver. db.addresses.ensureIndex( { "user_id": 1 }, { unique: true } ) Error Ignored
  35. 35. 35  With an unacknowledged write concern, MongoDB does not acknowledge the receipt of write operation.  Unacknowledged is similar to errors ignored; however, drivers attempt to receive and handle network errors when possible.  Write operation to a mongod instance with write concern of unacknowledged.  The client does not wait for any acknowledgment. Driver mongod Write Apply Unacknowledged
  36. 36. 36  With a receipt acknowledged write concern, the mongod confirms the receipt of the write operation.  Acknowledged write concern allows clients to catch network, duplicate key, and other errors.  To set acknowledged write concern, specify w values of 1 to your driver.  MongoDB uses acknowledged write concern by default, after the releases outlined in Default Write Concern Change.  Write operation to a mongod instance with write concern of acknowledged.  The client waits for acknowledgment of success or exception. Acknowledged
  37. 37. 37 Driver mongod Write Apply getLastErrorW:l getLastError Response Acknowledged
  38. 38. 38  With a journaled write concern, the mongod acknowledges the write operation only after committing the data to the journal.  This write concern ensures that MongoDB can recover the data following a shutdown or power interruption.  To set a journaled write concern, specify w values of 1 and set the journal or j option to true for your driver.  With a journaled write concern, write operations must wait for the next journal commit.  To reduce latency for these operations, you can increase the frequency that MongoDB commits operations to the journal.  The mongod sends acknowledgment after it commits the write operation to the journal. Journaled
  39. 39. 39 Driver mongod Write Apply getLastErrorj:true getLastError Response Write to Journal Journaled
  40. 40. 40  Replica sets add several considerations for write concern.  Basic write concerns affect write operations on only 1 mongod instance.  The w argument to getLastError provides replica acknowledged write concerns.  With replica acknowledged you can guarantee that the write operation propagates to the members of a replica set.  To set replica acknowledged write concern, specify w values greater than 1 to your driver. Replica Acknowledged
  41. 41. 41 Driver Primary Write ApplygetLastErrorW:2 getLastError Response Secondary Secondary Replicate Replica Acknowledged
  42. 42. 42 Write Operations Performance Document Growth JournalingIndexes Storage Performance Write Operation Performance
  43. 43. 43 Annie’s Question What is record padding?
  44. 44. 44 Annie’s Answer Padding is a process to minimize document movements.
  45. 45. 45 String: Used to store the string data. String in mongodb must be UTF-8 valid. Arrays: This type is used to store arrays or list or multiple values into one key. Object: This datatype is used for embedded documents. Code: To store javascript code into document. Time Stamp: For recording when a document has been modified or added. Integer: For numerical value. Integer can be 32 bit or 64 bit depending upon your server. Boolean: For a Boolean (true/ false) value. Double: For floating point values. Regular expression: To store regular expression. Null: This type is used to store a Null value. Date: For current date or time in UNIX time format. Can specify your own date time by creating object of Date and passing day, month, year into it. Min/ Max keys: To compare a value against the lowest and highest BSON elements. Symbol: It's generally reserved for languages that use a specific symbol type. Object ID: Store the document’s ID. Binary data: To store binay data. MongoDB Data types
  46. 46. 46  Insert Documents  Query Documents  Limit Fields to Return from a Query  Iterate a Cursor in the mongo Shell  Analyze Query Performance  Modify Documents  Remove Documents  Perform Two Phase Commits  Create Tailable Cursor  Isolate Sequence of Operations  Create an Auto-Incrementing Sequence Field  Limit Number of Elements in an Array after an Update MongoDB CRUD Syntax & Queries
  47. 47. 47 MongoDB CRUD Operation- Live Demo
  48. 48. 48 Annie’s Question What is two phase commit?
  49. 49. 49 Annie’s Answer This is used to ensure immediate consistency and reliability.
  50. 50. 50 Your Questions
  51. 51. 51 ,_read,_update_and_delete      Further Reading
  52. 52. 52 Tasks for you Attempt the following Assignments using the documents present in the LMS: How to iterate a Cursor in the mongo Shell? How to close Inactive Cursors? What is Tailable Cursor? How can you create an Auto-Incrementing Sequence Field? What is Record Padding? How many methods are there to insert document in Collection? What is _id field in MongoDB? What all the operators are there in MongoDB What is capped collection? What is CRUD? Assignments
  53. 53. 53 Generate Test Data on MongoDB Database Execute all Module2 Script present in LMS Read FAQ Module2 in LMS Take Quiz in LMS for Module2 Complete assignment Pre-work: Module 2
  54. 54. 54 Agenda of the Next Class  Data Modeling Concepts  Type of Data Modeling  Why Data Modeling ?  Data Modeling Approach  Analogy Between RDBMS & MongoDB Data Model  MongoDB Data Model  Challenges for Data Modeling in MongoDB  Data Model Examples and Patterns  Data Model References  Use Case of Data modeling Module 3 Schema Design and Data Modeling
  55. 55. 55 What’s within the LMS Click here to expand and view all the elements of this Module
  56. 56. 56 What’s within the LMS Recording of the Class Presentation Scripts Assignment
  57. 57. 57 What’s within the LMS Further Reading Pre-work Quiz FAQ
  58. 58. Thank You See You in Class Next Week