MongoDB – Developer Level 1 & 2.
Evolution of Databases.
What is NoSQL Database?. A common misconception is that the term NoSQL stands for “No SQL”. NoSQL actually stands for” Not Only SQL”, to emphasize the fact that NoSQL databases are an alternative to SQL and can in fact, apply SQL-like query concepts. NoSQL covers any database, that is not a traditional relational database management system. The motivation behind NoSQL is mainly simplified design, horizontal scaling and finer control over the availability of data..
[Audio] WiredTiger is the default storage engine starting in MongoDB 3.2. It is well-suited for most workloads and is recommended for new deployments. WiredTiger provides a document-level concurrency model, checkpointing, and compression, among other features. In MongoDB Enterprise, WiredTiger also supports Encryption at Rest. MMAPv1 is the original MongoDB storage engine and is the default storage engine for MongoDB versions before 3.2. It performs well on workloads with high volumes of reads and writes, as well as in-place updates. The In-Memory Storage Engine is available in MongoDB Enterprise. Rather than storing documents on-disk, it retains them in-memory for more predictable data latencies..
MongoDB Overview. Collection Collection is a group of MongoDB documents. It is the equivalent of an RDBMS table. A collection exists within a single database. Collections do not enforce a schema. Documents within a collection can have different fields. Typically, all documents in a collection are of similar or related purpose..
MongoDB Overview. Document A document is a set of key-value pairs. Documents have dynamic schema. Dynamic schema means that documents in the same collection do not need to have the same set of fields or structure, and common fields in a collection's documents may hold different types of data..
MongoDB Overview. RDBMS Database Table Tuple/Row column Table Join Primary Key MysqId/Oracle mysql/sqlplus MongoDB Database Collection Document Field Embedded Documents Primary Key (Default key _ id provided by mongodb itself) Database Server and Client mongod mongo.
MongoDB Overview. Sample Document, ] }.
Advantages of MongoDB over RDBMS. Schema less : MongoDB is a document database in which one collection holds different documents. Number of fields, content and size of the document can differ from one document to another. Structure of a single object is clear. No complex joins. Deep query-ability. MongoDB supports dynamic queries on documents using a document-based query language that's nearly as powerful as SQL. Tuning..
Advantages of MongoDB over RDBMS. Ease of scale-out: MongoDB is easy to scale. Conversion/mapping of application objects to database objects not needed. Uses internal memory for storing the (windowed) working set, enabling faster access of data..
Why Use MongoDB?. Document Oriented Storage: Data is stored in the form of JSON style documents. Index on any attribute Replication and high availability Auto- sharding Rich queries Fast in-place updates Professional support by MongoDB MMAPv1 storage engine limits each database to no more than 16000 data files. This means that a single MMAPv1 database has a maximum size of 32TB . The maximum BSON document size is 16MB https://docs.mongodb.com/manual/reference/limits/.
Where to Use MongoDB?. Big Data Content Management and Delivery Mobile and Social Infrastructure User Data Management Data Hub.
Consistency. Primary x: "123" x: "789". Primary DB x-"123" Secondary DB x-"123" x = "709".
Consistency Choices -Complete. „69L„ = X „cz = x „GGL„ = X „6GL„ = X „CZ.
Consistency Choices –Fire & Forget. x = "123 x = "123 x = "789 x = "1 23.
Consistency Choices -Majority. x = "123 x = "123 x = "789 x = "123 x = "789.
Demo. Installation Connecting to MongoDB mongod Mongo Help – db.help () Statistics – db.stats () Configuration – mongod.conf To Start mongod - > mongod –f < config file> Install as service - mongod - > mongod –f < config file> --install.
MongoDB Data Modeling. Data in MongoDB has a flexible schema.documents in the same collection. They do not need to have the same set of fields or structure, and common fields in a collection’s documents may hold different types of data..
MongoDB Data Modeling -Best Practices. Design your schema according to user requirements. Combine objects into one document if you will use them together. Otherwise separate them (but make sure there should not be need of joins). Duplicate the data (but limited) because disk space is cheap as compare to compute time. Do joins while write, not on read. Optimize your schema for most frequent use cases. Do complex aggregation in the schema.
MongoDB – Create/Drop Database. Command : use DATABASE_NAME The command will create a new database if it doesn't exist, otherwise it will return the existing database. To list the DBs - show dbs Insert data - db.users.insert () To drop database – db.dropDatabase () Demo.
MongoDB - Create Collection. db.createCollection (name, options).
MongoDB - Create Collection. Options Parameter. Field Type Description capped Boolean (Optional) If true, enables a capped collection. Capped collection is a fixed size collection that automatically overwrites its oldest entries when it reaches its maximum size. If you specify true, you need to specify size parameter also. autoIndexID Boolean (Optional) If true, automatically create index on _id field.s Default value is false. size number (Optional) Specifies a maximum size in bytes for a capped collection. If capped is true, then you need to specify this field also. max number (Optional) Specifies the maximum number of documents allowed in the capped collection..
MongoDB – Collection methods. To create collection - db.createCollection (" mycollection ") To display collections - show collections To drop collections - db.COLLECTION_NAME.drop () Demo/Exercise.
MongoDB - Datatypes. String Integer Boolean Double Arrays Timestamp Object Date Object ID Binary data Regular expression.
MongoDB – Insert/Update Document. To insert data into MongoDB collection, you need to use MongoDB's insert() or save() method. db.COLLECTION_NAME.insert (document) db.collection.insert db.collection.insertOne db.collection.insertMany To drop db. COLLECTION_NAME.drop () db.COLLECTION_NAME.update (SELECTIOIN_CRITERIA, UPDATED_DATA) - updates the values in the existing document.
MongoDB – Insert/Update Document. To replace the existing document - db.COLLECTION_NAME.save ().
MongoDB - Query Document. To query data from MongoDB collection, you need to use MongoDB's find() method. db.COLLECTION_NAME.find () To display the results in a formatted way, you can use pretty() method. db.mycol.find ().pretty() db.mycol. findOne () Projection - to return specific fields from collections.
MongoDB – RDBMS Vs MongoDB. Operation Syntax Example RDBMS Equivalent Equality db.mycol.find ().pretty() where by = ‘Sonata' Less Than} db.mycol.find(}).pretty() where likes < 50 Less Than Equals} db.mycol.find (}).pretty() where likes <= 50 Greater Than} db.mycol.find (}).pretty() where likes > 50 Greater Than Equals} db.mycol.find (}).pretty() where likes >= 50 Not Equals} db.mycol.find(}).pretty() where likes != 50.
MongoDB - Query Document – AND/OR. db.mycol.find (, ] } ).pretty() db.mycol.find (, ] } ).pretty().
Indexes. MongoDB creates a unique index on the _id field during the creation of a collection..
Indexes. db.collection.createIndex ( <key and index type specification>, <options> ) Single field index - MongoDB supports indexes that include content on a single field, as well as compound indexes that include content from multiple fields . Compound index - MongoDB allows you to specify a unique constraint on an index. These constraints prevent applications from inserting documents that have duplicate values for the inserted fields . Text Index -MongoDB provides text indexes to support text search queries on string content. text indexes can include any field whose value is a string or an array of string elements..
MongoDB - Delete Document. MongoDB's remove() method is used to remove a document from the collection. deletion criteria − (Optional) deletion criteria according to documents will be removed. justOne − (Optional) if set to true or 1, then remove only one document. If you don't specify deletion criteria, then MongoDB will delete whole documents from the collection. Syntax - db.COLLECTION_NAME.remove (DELLETION_CRITTERIA,JUSTONE).
MongoDB - Aggregation. Aggregations operations process data records and return computed results. Aggregation operations group values from multiple documents together, and can perform a variety of operations on the grouped data to return a single result. Syntax : db.COLLECTION_NAME.aggregate (AGGREGATE_OPERATION).
MongoDB – Aggregation Example. db.books.aggregate ( [} }] ) SQL : SELECT publisher as _id, count(name) as total from books group by publisher.
MongoDB – Aggregation expressions. $sum - Sums up the defined value from all documents in the collection. $ avg - Calculates the average of all given values from all documents in the collection. $min - Gets the minimum of the corresponding values from all documents in the collection. $max - Gets the maximum of the corresponding values from all documents in the collection..
MongoDB – Aggregation expressions. $push - Inserts the value to an array in the resulting document. $ addToSet - Inserts the value to an array in the resulting document but does not create duplicates. $first - Gets the first document from the source documents according to the grouping. $last - Gets the last document from the source documents according to the grouping..
MongoDB – Aggregation Pipeline. Documents enter a multistage processing pipeline, where they gets transformed into an aggregated result. $project: Used to select some specific fields from a collection. $match: This is a filtering operation and thus this can reduce the amount of documents that are given as input to the next stage. $group: This does the actual aggregation as discussed above. $sort: Sorts the documents.
MongoDB – Aggregation Pipeline. $skip: With this, it is possible to skip forward in the list of documents for a given amount of documents. $limit: This limits the amount of documents to look at, by the given number starting from the current positions..
MongoDB - Replication. Replication is the process of synchronizing data across multiple servers. Replication provides redundancy and increases data availability with multiple copies of data on different database servers. Replication protects a database from the loss of a single server. Replication also allows you to recover from hardware failure and service interruptions. With additional copies of the data, you can dedicate one to disaster recovery, reporting, or backup..
Why Replication?. To keep your data safe High (24*7) availability of data Disaster recovery No downtime for maintenance (like backups, index rebuilds, compaction) Read scaling (extra copies to read from) Replica set is transparent to the application.
MongoDB replication. Cli ent Appl i cation D river Writes Re ds Prirna Seconda Seconda.