0% found this document useful (0 votes)
4 views

MONGODBNOTES

The document provides comprehensive notes on MongoDB, covering its introduction, installation, and usage through MongoDB Compass and Shell. It details CRUD operations, including creating databases and collections, inserting, querying, updating, and deleting documents, as well as data types used in MongoDB. Additionally, it includes practical examples and commands for performing various operations within MongoDB.

Uploaded by

lizameldrid001
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

MONGODBNOTES

The document provides comprehensive notes on MongoDB, covering its introduction, installation, and usage through MongoDB Compass and Shell. It details CRUD operations, including creating databases and collections, inserting, querying, updating, and deleting documents, as well as data types used in MongoDB. Additionally, it includes practical examples and commands for performing various operations within MongoDB.

Uploaded by

lizameldrid001
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

RITIKA LALA

USCS406 Notes UNIT 1 MONGODB

MongoDB(M): Introduction to MongoDB. Installing MongoDB.


Using MongoDB Compass. Using Mongo Shell Interface.
Connecting to MongoDB. Creating Schemas and Models.
Querying Documents Using find(). Inserting Documents Using
create(). Updating Documents Using findOneAndUpdate().
Deleting Documents Using findOneAndDelete() & deleteMany()

Q1) INTRODUCTION OF MONGODB/ WHAT IS MONGODB?


1) MongoDB is NoSQL database. The name Mongo comes from
the word “humongous”.
2) It is document-oriented database . MongoDB is a document
database. It stores data in a type of JSON format called BSON.
3) data is stored in the database as a form of JSON objects rather
than the traditional columns and rows of a relational database
4) It is open source database. A record in MongoDB is a
document, which is a data structure composed of key value pairs
similar to the structure of JSON objects.

5) Records in a MongoDB database are called documents, and


the field values may include numbers, strings, Booleans, arrays,
or even nested documents.

6) 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.

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.

Q3) What is MongoDB Compass and Shell Interface?

To download Compass, you can use your preferred web browser.

1. Open the downloads page.


https://www.mongodb.com/try/download/shell
2. Select the installer you prefer. The MongoDB
Compass installer is available as a .exe or .msi package or
a .zip archive.
3. Download the latest version of MongoDB Compass for
Windows.
What is MongoDB Compass?
MongoDB Compass is a powerful GUI for querying, aggregating,
and analyzing your MongoDB data in a visual environment.
Compass is free to use and source available, and can be run on
macOS, Windows, and Linux.

MongoDB Shell Download:

https://www.mongodb.com/try/download/shell

MongoDB Shell is the quickest way to connect to (and work with)


MongoDB. MongoDB Shell is an open source (Apache 2.0),
standalone product developed separately from the MongoDB
Server.

T o start the shell, open command prompt, run it as a


administrator then run the mongo executable:

3
Type in one cmd: monogd
Type in another cmd: mongo
It will start MongoDB shell.

Q4) Mention some MongoDB shell commands The following


list describes each command and its purpose:
1) help : Displays syntax help for MongoDB shell commands.
The option argument allows you to specify an area where you
want help.
2) use : Changes the current database handle. Database
operations are processed on the current database handle.
3) db.help: Displays help options for the database methods.
4) show : Shows a list based on the option argument. The value
of option can be: dbs: Displays a list of databases.
collections: Displays a list of collections for the current database.
5) db.dropDatabase() - drop the current database.

Q5) What is collection and documents in MongoDB?


1) MongoDB groups data together through collections.
2) 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.
3) A collectionis simply a grouping of documents that have the
same or a similar purpose.
4) A collection acts similarly to a table in a traditional SQL
database, with one major difference.
5) In MongoDB, a collection is not enforced by a strict schema;
instead, documents in a collection can have a slightly
different structure from one another as needed. A document
is a representation of a single entity of data in the MongoDB

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.

Q6) List various data types used in MongoDB.


1) The BSON data format provides several different types that are
used when storing the JavaScript objects to binary form.
1. Null
2. Numbers (32-bit integer, 64-bit integer, Double)
3. String
4. Object
5. Array
6. Binary Data
7. Boolean
8. Date, Timestamp
10. Regular Expression
Topic: Connecting to MongoDB. Creating Schemas and
Models,
For connecting to MongoDB there are two ways one is through
MongoDB Compass/Shell 2) Through Node JS
Q7) Perform the following activities in mongodb using MongoDB
Shell.
Open cmd and type mongod and in another cmd type mongo and
than you will get Cursor >
1) Create database “inventory”, & create collection “products” &
add 5 product documents in it. For collection “products”, details

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

Insert Many documents together:


> db.product.insertMany(
{"productno":"p1","description":"earphone","company":"oneplus","
price":8000},

6
{"productno":"p2","description":"desktop","company":"apple",
"price":120 000},

{"productno":"p3","description":"smartwatch","company":"sa
msung","pric e":17000} );

Topic: Querying Documents Using find()


2) List products of “Samsung”.
> db.product.find();
Or
> db.product.find().pretty();
3) Display products by Productno and company.
• To show specific data by “productno” & “company”:
> db.product.find({productno:"p3"});
> db.product.find({company:"samsung"});

3) List products in ascending /descending order of their price.


(remember for ascending : 1 , descending : -1 )
> db.product.find().sort({"price":1}).pretty();
> db.product.find().sort({"price":-1}).pretty();
4) List products whose price is more than 15000.
> db.product.find({"price":{$gt:15000}}).pretty();

5) Update price of product “p1” to 10000


> db.product.update({"productno": "p1"},{$set:{"price":10000}});

6) Check the above product p1 is updated or not


> db.product.find({"productno":"p1"}).pretty();
7
7) 6) Drop database.
> db.dropDatabase()

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

2) List all student details:


> db.result.find().pretty();

3) List students who have scored more than 500 marks:


> db.result.find({marks:{$gt:500}}).pretty();
4) List students of tycs in ascending order of marks:
> db.result.find().sort({"marks":1}).pretty();
5) Update marks of seatno: 202 to 750.
• Update marks of seatno=202:
> db.result.update({"seatno":202}, {$set:{"marks":750}});
• Check the updated marks:
> db.result.find({"seatno":202}).pretty();

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)

Mongodb CRUD Operations:


Create database blog
➢ use blog
There are 2 ways to create a collection
You can create a collection using the createCollection() database
method.
➢ db.createCollection("posts")
You can also create a collection during the insert process.
➢ db.posts.insertOne({"title": "Post 1"})
Insert Documents
There are 2 methods to insert documents into a MongoDB
database.
➢ insertOne()
To insert a single document, use the insertOne() method.This
method inserts a single object into the database.
db.posts.insertOne({ title: "Post Title 1", body: "Body of post.",
category: "News", likes: 1, tags: ["news", "events"], date: Date()});
insertMany()
To insert multiple documents at once, use the insertMany()
method.This method inserts an array of objects into the
database.
db.posts.insertMany ( [ { title: "Post Title 2", body: "Body of post.",
category: "Event", likes: 2, tags: ["news", "events"], date: Date() },
{ title: "Post Title 3", body: "Body of post.", category:
"Technology", likes: 3, tags: ["news", "events"], date: Date() },

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.

db.collection.findOneAndDelete( filter, options )


db.scores.findOneAndDelete( { "name" : "M. Tagnum" } );

Write a MongoDB command which make use of findone and


update.
db.collection.findOneAndUpdate( filter, update, options )

db.grades.insert({ _id: 6234, name : "R. Stiles", "assignment" : 1,


"points" : 10 }
);
db.grades.findOneAndUpdate( { "name" : "R. Stiles" }, { $inc: {
"points" : 5 } } )
//this will update points by 5.

14

You might also like