MONGODBNOTES
MONGODBNOTES
Example: {
title: "Post Title 1",
body: "Body of post.",
category: "News",
likes: 1,
1
tags: ["news", "events"],
date: Date()
}
5) MongoDB provides High scalability: MongoDB’s structure
makes it easy to scale horizontally by sharing the data across
multiple servers.
6) MongoDB provides High performance: MongoDB is one of the
highest-performing databases available. Especially today, with
more and more people interacting with websites, it is important
to have a backend that can support heavy traffic.
7) MongoDB is No SQL injection: MongoDB is not susceptible to
SQL injection
8) MongoDB is a NoSQL database based on a document model
where data objects are stored as separate documents inside a
collection. The motivation of the MongoDB language is to
implement a data store that provides high performance, high
availability, and automatic scaling.
9) MongoDB is simple to install and implement.
Topic: Installing MongoDB.
Q2) How to install MongoDB?
Installing MongoDB follow the steps:
1) http://docs.mongodb.org/manual/installation/. Go to this
link and download server
(https://www.mongodb.com/try/download/community)
2) Download and extract the MongoDB files.
3) Create a data files directory: /data/db. Or in C:\data\db
folder
4) set Mongodb path as system path.
5) Start MongoDB using the following command from the console
prompt:
6) Start mongod.exe from command prompt from mongodb\bin
folder
2
7) Once you have installed MongoDB, you need to be able to start
and stop the database engine. The database engine starts by
executing the mongod(mongod.exe on Windows) and stop
mongod.exe or shutdown server
Topic: Using MongoDB Compass. Using Mongo Shell
Interface.
https://www.mongodb.com/try/download/shell
3
Type in one cmd: monogd
Type in another cmd: mongo
It will start MongoDB shell.
4
database. A collection is made up of one or more related
documents.
6) The maximum size of a document in MongoDB is 16MB.
7) 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.
5
like (productno, description, company, price) need to be
maintained.
Create database named “inventory”:
> use inventory
Topic: Create Schemas/collections and Inserting Documents
Using create()
➢ db.createCollection(“Product”);
or direct insert document which will automatically create
collection Product.
• Insert some values in collection named “product”: insert
one by one document
>
db.product.insert({"productno":"p1","description":"earphone","com
pany":"oneplus","price":8000});
>
db.product.insert({"productno":"p2","description":"desktop","comp
any":"apple","price":120 000});
>
db.product.insert({"productno":"p3","description":"smartwatch","c
ompany":"samsung","pric e":17000});
>
db.product.insert({"productno":"p4","description":"speaker","comp
any":"jbl","price":13000} );
>
db.product.insert({"productno":"p5","description":"smartphone","c
ompany":"samsung","pri ce":14000});
6
{"productno":"p2","description":"desktop","company":"apple",
"price":120 000},
{"productno":"p3","description":"smartwatch","company":"sa
msung","pric e":17000} );
Second Example:
#OPERATIONS(PART-B):
1) Create database “exam” & create collection “result” to store
student marks. For collection
“result”, details like (seatno, name, class, marks, grade) need to
be maintained. Grades are (F,
D, C, B, A, O)
2) List all student details.
3) List students who have scored more than 500 marks.
4) List students of tycs in ascending order of marks.
5) Update marks of seatno: 202 to 750.
#STEPS(PART-B):
1) Create database “exam” & create collection “result” to store
student marks. For collection
“result”, details like (seatno, name, class, marks, grade) need to
be maintained. Grades are (F,
D, C, B, A, O)
• Create database named “exam”:
> use exam
Insert some values in collection named “result”:
> db.result.insert({"seatno":201, "name":"jim", "class":"tycs",
"marks":540, "grade":"C"});
> db.result.insert({"seatno":202, "name":"jam", "class":"tycs",
"marks
":670, "grade":"B"});
8
> db.result.insert({"seatno":203, "name":"tim", "class":"tycs",
"marks":780, "grade":"B"});
> db.result.insert({"seatno":204, "name":"tam", "class":"tycs",
"marks":202, "grade":"F"});
> db.result.insert({"seatno":205, "name":"sim", "class":"tycs",
"marks":910, "grade":"O"});
Third Example:
#OPERATIONS(PART-C):
1) Create database “Library”. Create collection of “books” & add 5
documents in it. For “books”
collection details like (isbnno, title, publisher, author, category,
price) need to be maintained.
2) List the Title, ISBN, Author for “books”.
3) List the books which price is more than 1500.
9
4) Remove the book (ISBN 10201) from collection.
5) List the ‘Pearsons’ publishers’ books.
6) List first 3 records.
#STEPS(PART-C):
1) Create database “Library”. Create collection of “books” & add 5
documents in it. For “books”
collection details like (isbnno, title, publisher, author, category,
price) need to be maintained.
• Create database named “Library”:
> use Library
• Insert some values in collection named “books”:
>db.books.insert({"isbnno":10201,"title":"Junglee","publisher":"Bo
okies","author":"Arthur","category":"Nature","price":650})
>db.books.insert({"isbnno":10202,"title":"Flyers","publisher":"Book
ies","author":"Ada","category":"Birds","price":600})
>db.books.insert({"isbnno":10203,"title":"Jewels","publisher":"Pear
sons","author":"Kiwie","category":"Women","price":1550})
>db.books.insert({"isbnno":10204,"title":"Flowers","publisher":"Pea
rsons","author":"PA","category":"Nature","price":6650})
>db.books.insert({"isbnno":10205,"title":"Talkers","publisher":"Pag
ers","author":"lizzie","category":"Gossip","price":1650})
2) List the Title, ISBN, Author for “books”.
• > db.books.find({},{"isbnno":1,"title":1,"author":1}).pretty();
3) List the books which price is more than 1500.
• > db.books.find({price:{$gt:1500}}).pretty();
4) Remove the book (ISBN 10201) from collection.
> db.books.remove({"isbnno": 10201}, 1);
• Check if it has been removed:
> db.books.find({ },{"isbnno":1}).pretty();
10
5) List the ‘Pearsons’ publishers’ books.
• > db.books.find({publisher:"Pearsons"}).pretty();
6) List first 3 records.
• > db.books.find().limit(3)
11
{ title: "Post Title 4", body: "Body of post.", category: "Event",
likes: 4, tags: ["news", "events"], date: Date() }
])
Query MongoDB Data:There are 2 methods to find and select
data from a MongoDB collection, find() and findOne(). find()
To select data from a collection in MongoDB, we can use the
find() method.This method accepts a query object. If left empty,
all documents will be
returned.
db.posts.find()
findOne()-To select only one document, we can use the findOne()
method.This method accepts a query object. If left empty, it will
return the first
document it finds.Note: This method only returns the first match
it finds.
Querying Data:-To query, or filter, data we can include a query in
our find() or findOne() methods.
db.posts.find( {category: "News"} )
Projection:Both find methods accept a second parameter called
projection. This parameter is an object that describes which fields
to include in the results.
Note: This parameter is optional. If omitted, all fields will be
included in the results.This example will only display the title
and date fields in the results.
db.posts.find({}, {title: 1, date: 1}
We use a 1 to include a field and 0 to exclude a field.
db.posts.find({}, {_id: 0, title: 1, date: 1}) Let's exclude the date
category field. All other fields will be included in the results.
db.posts.find({}, {category: 0})
We will get an error if we try to specify both 0 and 1 in the same
object.
12
db.posts.find({}, {title: 1, date: 0})
Update Document
To update an existing document we can use the updateOne() or
updateMany() methods. The first parameter is a query object to
define which document or documents should be updated. The
second parameter is an object defining the updated data.
updateOne()- The updateOne() method will update the first
document that is found matching the provided query.
Let's see what the "like" count for the post with the title of "Post
Title 1":
db.posts.find( { title: "Post Title 1" } )
[{
_id: ObjectId("62c350dc07d768a33fdfe9b0"), title: 'Post Title 1',
body: 'Body of post.', category: 'News', likes: 1, tags: [ 'news',
'events' ], date: 'Mon Jul 04 2022 15:43:08 GMT-0500 (Central
Daylight Time)' } ]
Now let's update the "likes" on this post to 2. To do this, we need
to use the $set operator.
db.posts.updateOne( { title: "Post Title 1" }, { $set: { likes: 2 }})
You can check by writing db.posts.find( { title: "Post Title 1" } )
Insert if not found, If you would like to insert the document if it is
not found, you can use the upsert option.
db.posts.updateOne( { title: "Post Title 5" }, { $set: { title: "Post
Title 5", body: "Body of post.", category: "Event", likes: 5, tags:
["news", "events"],
date: Date() } }, { upsert: true } )
Topic: Updating Documents Using findOneAndUpdate().
Deleting Documents Using findOneAndDelete() &
deleteMany()
We can delete documents by using the methods deleteOne() or
deleteMany(). These methods accept a query object. The matching
documents will be deleted.deleteOne() The deleteOne()
13
method will delete the first document that matches the query
provided.
db.posts.deleteOne({ title: "Post Title 5" })
deleteMany()-The deleteMany() method will delete all documents
that match the query provided.
db.posts.deleteMany({ category: "Technology" })
Write a MongoDB command which finds the first document
where name : M. Tagnum and deletes it.
14