UNIT – IV Mongo DB Mongo DB: Understanding Mongo DB and NoSQL, Mongo DB Data Types, planning your Data Model, Building the Mongo DB Environment, Administering User Accounts, Configuring Access Control, Database update Operators, Adding Documents to a Collection, Updating Documents in a Collection, Deleting Documents from a Collection, Removing a Single Document from a Collection.
Why Database What is SQL? SQL stands for Structured Query Language SQL lets you access and manipulate databases Using SQL in Your Web Site To build a web site that shows data from a database, you will need: An RDBMS database program (i.e. MS Access, SQL Server, MySQL) To use a server-side scripting language, like PHP or ASP To use SQL to get the data you want To use HTML / CSS to style the page
What is MongoDB ? MongoDB is an open source NoSQL database management program. NoSQL (Not only SQL) is used as an alternative to traditional relational databases. NoSQL databases are quite useful for working with large sets of distributed data . MongoDB is a document base database. It stores data in a type of JSON format called BSON(Binary JSON).
A record in a MongoDB is a document , which is a data structure composed of key value pairs similar to the structure of JSON objects. MongoDB is a document database and can be installed locally or hosted in the cloud.
MongoDB is used for high-volume data storage, helping organizations store large amounts of data while still performing rapidly. Organizations also use MongoDB for its ad-hoc queries, indexing, load balancing, aggregation, server-side JavaScript execution and other features. Structured Query Language (SQL) is a standardized programming language that is used to manage relational databases. SQL normalizes data as schemas and tables, and every table has a fixed structure.
Instead of using tables and rows as in relational databases, as a NoSQL database, the MongoDB architecture is made up of collections and documents. Documents are made up of Key-value pairs -- MongoDB's basic unit of data. Collections, the equivalent of SQL tables, contain document sets. MongoDB offers support for many programming languages, such as C, C++, C#, Go, Java, Python, Ruby and Swift.
What is BSON in mongoDB ? MongoDB stores document(objects) in a format called BSON.BSON is a binary serialization of JSON-like documents. BSON stands for “Binary JSON”, but also contains extensions that allow representation of data types that are not part of JSON. for ex, BSON has a Data and BinData types
Understanding Mongo DB and NoSQL What is NoSQL Database? NoSQL database stands for “Not only SQL” or “Not SQL”, Originally it is referring to “non-SQL” or “non-relational”. NoSQL provides flexible schemas and scales easily with large amounts of data and high user loads. NoSQL databases are flexible, scalable, high- performance,and highly functional databases to provide great user experiences.
What are the different Types of NoSQL Databases? There are the four main types of NoSQL databases: Document databases Key-value stores Wide-column stores Graph stores
Data Types In MongoDB JSON and BSON I t is important to have an understanding of how MongoDB stores data. MongoDB and many other document-based NoSQL databases use JSON (JavaScript Object Notation) to represent data records as documents . There are many advantages to using JSON to store data. Some of them being: easy to read, learn, and its familiarity among developers flexibility in format, whether sparse, hierarchical, or deeply nested self-describing, which allows for applications to easily operate with JSON data allows for the focus on a minimal number of basic types JSON supports all the basic data types like string, number, boolean , etc. MongoDB actually stores data records as Binary-encoded JSON ( BSON ) documents.
String name : " Jhon “ Double marks: 97.6 Integer age: 22 Array In MongoDB , the array is represented by the square brackets [ ]. The array can have multiple values of the same or different data types. subjects: [ "English", "Social Studies", "Economics" ], Object To store the nested documents, we use the object data type . address: {city: "New York", country: "USA"}
Boolean Either true or false is stored in the boolean data type. pass: true Null The null values are stored in the null data type . lastname : null Date The date data type in MongoDB is used to store the date. We can specify a custom date by passing day, month, and year to the date object . birth: new Date('Jun 23, 2000')
Data Model Design MongoDB provides two types of data models: — Embedded data model and Normalized data model. Based on the requirement, you can use either of the models while preparing your document.
Normalized Data Model In this model, you can refer the sub documents in the original document, using references. For example, you can re-write the above document in the normalized model as : Employee: { _id: <ObjectId101>, Emp_ID : "10025AE336" }
Building the Mongo DB Environment Install MongoDB On Windows
Mongo DB create Database
//to display the list od databases show dbs //to swith to database or to create database use db_name //To display list of colletions in a selected database show collections //To create collection and to insert document into collection db.collection_name.insertOne ({" Name":"Hi "}) db.collection_name.insertMany ([{" Name":"Hi "},{" Name":"Bye "}])
//Commands to perform read operation db.stu.find ({Age:{$in:[20,21]}}) db.stu.find ({ CIty :" Hyd ",Age:{$gte:20}}) ($ lt , $ lte , $ gt , $ gte ) db.stu.find ({},{Name:1}) db.stu.find ({},{_id:0}) demo> db.stu.find ({},{Name:1,Rollno:1}) demo> db.stu.find ({},{_id:0,Name:1,Rollno:1}) db.stu.find ({$or:[{ CIty :" Hyd "},{Age:20}]})
//command to perform UPDATE operation db.stu.updateOne({Name:"Sai"},{$set:{Age:20}}) db.stu.updateMany({Name:"Sai"},{$set:{Age:20}}) //To delete all documents from a collection db.movies.deleteMany({}) //To delete selected document from a collection db.movies.deleteMany( { Name: "Sai" } ) db.movies.deleteOne( { Name: "Sai" } )
//To create admin user db.createUser({user:"admin",pwd:"mru",roles:[{role:"readWrite",db:"config"}]}) // to display list of users show users //To create a normal user with out roles db.createUser({user:"userone",pwd:"mru",roles:[]}) //To create a user with specific roles db.createUser({user:"usertwo",pwd:"mru",roles:[{role:"readWrite",db:"demo"}]})
MongoDB - Drop Database
MongoDB Create Collection
MongoDB Drop Collection
MongoDB Insert Document
MongoDB Query API
MongoDB Projection
MongoDB – Update() Method The update() method updates the values in the existing document in the collections of MongoDB. When you update your document the value of the _id field remains unchanged. By default, the db.collection.update() method updates a single document. Include the option multi: true to update all documents that match the given query. This method can be used for a single updating of documents as well as multiple documents. Note: In MongoDB, the update() method has been deprecated in favor of using updateOne() or updateMany() depending on your specific use case.
MongoDB updateOne() Method – db.Collection.updateOne() In MongoDB, updateOne() method updates a first matched document within the collection based on the given query. When you update your document the value of the _id field remains unchanged. This method updates one document at a time and can also add new fields in the given document. It takes three parameters, the first one is the selection criteria to update the document, the second one is the new data to be updated, and the remaining are optional.
MongoDB updateMany() Method – db.Collection.updateMany() The updateMany() method updates all the documents in MongoDB collections that match the given query. When you update your document, the value of the _id field remains unchanged. This method can also add new fields in the document. Specify an empty document({}) in the selection criteria to update all collection documents. db.Collection_name.updateMany({Selection_Criteria},{$set:{Update_Data}})
MongoDB – db.collection.findOneAndUpdate() Method The findOneAndUpdate() method updates the first matched document in the collection that matches the selection criteria. If more than one document matched the selection criteria then it updates only the first matched document. When we update the document, the value of the _id field remains unchanged. This method will return the original document but if we want to return the updated document then we have to set the value of the returnNewDocument parameter to true.
User Management in MongoDB User management methods are used to manage the user access to the database.
Database update Operators
EX:
Data Modelling in MongoDB Data modeling is the process of arranging unstructured data that comes from a real-world event into a logical data model in a database . D ata modeling helps you better understand the data at hand and identify future business requirements. Different Types of Data Models Conceptual data model Logical data model Physical data model
MongoDB Update Operators Fields The following operators can be used to update fields : $ currentDate : Sets the field value to the current date db.stu.updateOne ({Name:" Nani "},{$ currentDate :{ JoiningDate:true }}) $ inc : Increments the field value db.stu.updateOne ({Name:" Nani "},{$ inc :{Age:1}}) $rename: Renames the field db.stu.updateOne ({Name:" Nani "},{$rename:{ JoiningDate :"JD"}}) $set: Sets the value of a field db.stu.updateOne ({Name:" Nani "},{$set:{Age:21}}) $unset: Removes the field from the document db.stu.updateOne ({Name:" Nani "},{$unset:{ JD:true }})
Array The following operators assist with updating arrays. $ addToSet : Adds distinct elements to an array db.stu.update ({Name:" Nem "},{$ addToSet :{ sub:"JS "}}) $pop: Removes the first or last element of an array db.stu.update ({Name:" Nem "},{$pop:{Marks:1}}) $pull: Removes all elements from an array that match the query db.stu.update ({Name:" Nem "},{$pull:{ sub:"C "}}) $push: Adds an element to an array db.stu.update ({Name:" Nem "},{$push:{ sub:"C "}}) $min: db.stu.updateOne ({Name:" Nani "},{$min:{Age:20}}) $max: db.stu.updateOne ({Name:" Nani "},{$ max:{ Age:20 }}) $ mul:db.stu.update ({Name:" Nani "},{$ mul :{Marks:2}})