UNIT-IV MongoDB
UNIT-IV MongoDB
MongoDB
• MongoDB is an open-source document
database and leading NoSQL database.
• MongoDB is written in C++.
• MongoDB is a cross-platform, document
oriented database that provides,
high performance, high availability, and easy scalability.
• MongoDB works on concept of collection and document.
Why MongoDB?
MySql Vs MongoDB
MongoDB in Web Applications
Collections & documents
Data Representation in JSON
Relationship of RDBMS terminology with MongoDB
MongoDB Terminology
• Database
• Database is a physical container for collections.
• Collection
• Collection is a group of MongoDB documents. It is the equivalent of
an RDBMS table.
• Document
• A document is a set of key-value pairs.
• Documents have dynamic schema.
Example of Document-Oriented Database
• MongoDB is a document-oriented database.
• It offers a document-oriented storage.
FirstName = “Ramesh",
Address = “Hyderabad",
Spouse = [{Name: "Anjali"}].
FirstName =“Madhu",
Address = “Banglore"
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.
• MongoDB supports dynamic queries on documents using a document-
based query language that's nearly as powerful as SQL.
String String is the most commonly used datatype. It is used to store data. A string must be UTF 8 valid in
mongodb.
Integer Integer is used to store the numeric value. It can be 32 bit or 64 bit depending on the server you are
using.
Boolean This datatype is used to store boolean values. It just shows YES/NO values.
Arrays This datatype is used to store a list or multiple values into a single key.
db.createCollection(“student”)
To get collections in a database
show collections
To drop a collection
db.students.drop()
Create database csit
CRUD Operations
C- Create
R- Retrieve
U-Update
D-Delete
Create collection(Table)
WriteResult({ "nInserted" : 1 })
To Count number of documents in a Collection
Find documents in a collection:
Update documents in a collection:
> db.student.updateOne({ rno: "100" }, { $set: { rno: "200" } })
> db.student.find()
{ "_id" : ObjectId("66318b27bb260e8e126b3197"), "rno" : "200",
"name" : "Ravi" }
{ "_id" : ObjectId("66318d32bb260e8e126b3198"), "rno" : "200",
"name" : "Ravi" }
{ "_id" : ObjectId("66318d35bb260e8e126b3199"), "rno" : "200",
"name" : "Ravi" }
{ "_id" : ObjectId("66318d36bb260e8e126b319a"), "rno" : "100",
"name" : "Ravi" }
Delete documents from a collection:
• > db.student.deleteOne({ rno: "100" })
• { "acknowledged" : true, "deletedCount" : 1 }
• > db.student.find()
• { "_id" : ObjectId("66318b27bb260e8e126b3197"), "rno" : "200",
"name" : "Ravi" }
• { "_id" : ObjectId("66318d32bb260e8e126b3198"), "rno" : "200",
"name" : "Ravi" }
• { "_id" : ObjectId("66318d35bb260e8e126b3199"), "rno" : "200",
"name" : "Ravi" }
Insert multiple documents into a collection:
db.<collection_name>.insertMany([
{ key1: "value1", key2: "value2" },
{ key1: "value3", key2: "value4" },
{ key1: "value5", key2: "value6" }
])
use library
db.books.insertMany([
{ title: "The Great Gatsby", author: "F. Scott Fitzgerald", year: 1925 },
{ title: "To Kill a Mockingbird", author: "Harper Lee", year: 1960 },
{ title: "1984", author: "George Orwell", year: 1949 }
])
Insert documents with custom "_id" values into a
collection:
db.<collection_name>.insertMany([
{ _id: 1, key1: "value1", key2: "value2" },
{ _id: 2, key1: "value3", key2: "value4" },
{ _id: 3, key1: "value5", key2: "value6" }
])
use store
db.products.insertMany([
{ _id: 101, name: "Laptop", price: 1200 },
{ _id: 102, name: "Smartphone", price: 800 },
{ _id: 103, name: "Tablet", price: 500 }
])
sort on books collection
{ "_id": 1, "title": "The Great Gatsby", "author": "F. Scott Fitzgerald", "price": 15 }
{ "_id": 2, "title": "To Kill a Mockingbird", "author": "Harper Lee", "price": 12 }
{ "_id": 3, "title": "1984", "author": "George Orwell", "price": 10 }
• use library
• db.books.find().sort({ price: 1 })
use store
db.products.updateMany(
{ category: "electronics" },
{ $set: { discount: 0.1 } }
)
Basic CRUD Operations
Relational Operators
Example data
• { "_id": 1, "name": "John", "age": 30 }
• { "_id": 2, "name": "Jane", "age": 25 }
• { "_id": 3, "name": "Bob", "age": 35 }
• { "_id": 4, "name": "Alice", "age": 28 }
Relational operators in MongoDB
• db.collection.find({ age: { $gt: 25 } }); _id 1, 3, and 4.
• db.collection.find({ age: { $lt: 30 } }); _id 2 and 4.
• db.collection.find({ age: { $gte: 25 } }); _id 1 and 3.
• db.collection.find({ age: { $lte: 30 } });
• db.collection.find({ name: { $eq: "John" } });
• db.collection.find({ name: { $ne: "John" } });
• db.users.find({ age: { $in: [25, 35] } });
• db.users.find({ age: { $nin: [25, 35] } });
Aggregate functions
Count the total number of students:
• db.students.aggregate([
• {
• $group: {
• _id: null,
• totalStudents: { $sum: 1 }
• }
• }
• ]);
Calculate the average age of students:
• db.students.aggregate([
• {
• $group: {
• _id: null,
• avgAge: { $avg: "$age" }
• }
• }
• ]);
Find the maximum and minimum age of students:
• db.students.aggregate([
• {
• $group: {
• _id: null,
• maxAge: { $max: "$age" },
• minAge: { $min: "$age" }
• }
• }
• ]);
Importing data to MongoDB
• import data from a JSON, CSV, or TSV file into a MongoDB collection.
• data.json
[
{"name": "John Doe", "age": 30, "email": "[email protected]"},
{"name": "Jane Smith", "age": 25, "email": "[email protected]"},
{"name": "Bob Johnson", "age": 35, "email": "[email protected]"}
]
Procedure to import data from CSV/JSON
Connect to the deployment containing the collection you wish to import data into.
2
You can either select the collection from the Collections tab or click the collection in the left-hand pa
Click the Add Data dropdown and select Import JSON or CSV file.4