0% found this document useful (0 votes)
40 views54 pages

UNIT-IV MongoDB

BDa Sem

Uploaded by

gaddamlokesh20
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views54 pages

UNIT-IV MongoDB

BDa Sem

Uploaded by

gaddamlokesh20
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

UNIT-IV

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.

• 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 working set, enabling faster access of
data.
MongoDB Datatypes
Data Types Description

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.

Double Double datatype stores floating point values.


Min/Max Keys This datatype compare a value against the lowest and highest bson elements.

Arrays This datatype is used to store a list or multiple values into a single key.

Object Object datatype is used for embedded documents.


Null It is used to store null values.
Symbol It is generally used for languages that use a specific type.
Date This datatype stores the current date or time in unix time format.
How to start Mongodb?
• To use MongoDB run the following command at
command prompt.
mongo
MongoDB Help
To get a list of commands, type db.help() in MongoDB client.
MongoDB Statistics
db.stats()
• To get stats about MongoDB server, type the command db.stats() in
MongoDB client. This will show the database name, number of
collection and documents in the database.
MongoDB - Create Database
• Syntax
use DATABASE_NAME
• The command will create a new database if it doesn't exist, otherwise
it will return the existing database.
• In MongoDB default database is test. If you didn't create any
database, then collections will be stored in test database.
• The dropDatabase() Method
db.dropDatabase()

MongoDB - Create Collection

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)

db.student.insertOne({ “rno”: “100“, “name”:”Ravi” })

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 })

{ "_id": 3, "title": "1984", "author": "George Orwell", "price": 10 }


{ "_id": 2, "title": "To Kill a Mockingbird", "author": "Harper Lee", "price": 12 }
{ "_id": 1, "title": "The Great Gatsby", "author": "F. Scott Fitzgerald", "price": 15 }
db.books.find().sort({ price: -1 })
{ "_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 }
Update all documents with a common field value:
• db.<collection_name>.updateMany({ <field>: <value_to_match> }, {
$set: { <field_to_update>: <new_value> } })

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

To import your formatted data into a collection:


1

Connect to the deployment containing the collection you wish to import data into.
2

Navigate to your target collection.

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

Select the appropriate file type.


Select either a JSON or CSV file to import and click Select.
Import command to use at termianl
mongoimport --db your_database_name --collection
your_collection_name --file your_json_file.json

You might also like