0% found this document useful (0 votes)
31 views91 pages

Mangodb v1 Manual

The document provides detailed installation steps for MongoDB and MongoDB Compass, including downloading, installation, and connecting to the command prompt. It also explains the definitions of MongoDB concepts such as documents, collections, and provides examples of CRUD operations. Additionally, it includes lab experiments and queries to practice MongoDB commands and operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views91 pages

Mangodb v1 Manual

The document provides detailed installation steps for MongoDB and MongoDB Compass, including downloading, installation, and connecting to the command prompt. It also explains the definitions of MongoDB concepts such as documents, collections, and provides examples of CRUD operations. Additionally, it includes lab experiments and queries to practice MongoDB commands and operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 91

MongoDB

(BDSL456B)

MongoDB Installation STEPS:

1. MongoDB Compass Downloading:

2. Choose MongoDB Community Server Download:

3. Opened this window

G.M.I.T Davanagere (Department of AI & ML) Page 1


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

4. Scroll Down
Choose 7.0.9(current), Windows 64,msi

5. Click on Download button

G.M.I.T Davanagere (Department of AI & ML) Page 2


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

6. Click on Save

7. MongoDB software is downloaded

G.M.I.T Davanagere (Department of AI & ML) Page 3


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

8. MongoDB Compass
Installation: Double click on this

9. Click on Next.

G.M.I.T Davanagere (Department of AI & ML) Page 4


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

10. Click on I accept the terms in the license agreement and press next.

11. Click on Next button…

G.M.I.T Davanagere (Department of AI & ML) Page 5


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

12. Click on Complete and click Next Button.

13. Select Run service as Network Service user and Click Next Button.

G.M.I.T Davanagere (Department of AI & ML) Page 6


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

14. Click on Next..

15. Click on Install

G.M.I.T Davanagere (Department of AI & ML) Page 7


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

16.Do you want to allow make appp changes? Click on Yes


and Wait…

17. Wait…

G.M.I.T Davanagere (Department of AI & ML) Page 8


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

18. Click on Finish.

19. MongDB software is installed and visible on desktop screen.

G.M.I.T Davanagere (Department of AI & ML) Page 9


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

Downloading steps for MongoShell….

1. Open google Chrome and Type MongoShell Select MongoDBShell


Download.

2. Scroll Download
Select Version: 2.2.5
Platform: Windows X64( 10+)
Package: Zip
Click On Download Button

G.M.I.T Davanagere (Department of AI & ML) Page 10


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

3. Now MongoDB Shell is Visible in Downloads File.

4. Now Extract The MongoDBShell.

G.M.I.T Davanagere (Department of AI & ML) Page 11


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

5. Open MongoDBShell Extracted File.

Now copy the mongosh document

G.M.I.T Davanagere (Department of AI & ML) Page 12


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

6. Next --->Go to This PC---->Select C Drive---->Program Files.

7. Next Program Files---->MongoDB

G.M.I.T Davanagere (Department of AI & ML) Page 13


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

8. MongoDB---->Server

9. Server---->7.0

10. 7.0---->Bin

G.M.I.T Davanagere (Department of AI & ML) Page 14


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

11. Bin---->Paste MongoShell Command

How to connect MongoDB to Command Prompt.

1. This PC-->C Drive-->Program Files-->MongoDB-->Server-->7.0--->Bin


Copy the Path Above Displayed

Open Command Prompt and Type CD (Change the Working Directory) and
Paste the Above Copied Path.

2. Type mongod Command for manages the Databases.

G.M.I.T Davanagere (Department of AI & ML) Page 15


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

3. Display The Result. Here MongoDB not Connected Because When


we need to Connect the MongoDB we should create an Folder
{"t":{"$date":"2024-05-09T11:33:07.094+05:30"},"s":"I",
"c":"CONTROL", "id":4615611, "ctx":"initandlisten","msg":"MongoDB
starting","attr":{"pid":16464,"port":27017,"dbPath":"C:/data/db/","archite
cture":"64-bit","host":"DESKTOP-9CJOCB0"}}

G.M.I.T Davanagere (Department of AI & ML) Page 16


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

4. This PC--->C Drive--->New Folder--->Rename New Folder to Data

5. Open Data Folder and Cretae One more Folder within the Data Folder.
6. Data Folder--->New Folder--->Rename New Folder to db.

G.M.I.T Davanagere (Department of AI & ML) Page 17


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

7. Now Open the Command Prompt again Type mongod----->Now


MongoDb is connected.

8. Minimize the Command Prompt.


9. Open another Command Prompt and Type mongosh (It shows either
MongoDB is Connected or Not and Display the which Version of
MongoDB and Mongosh used)

G.M.I.T Davanagere (Department of AI & ML) Page 18


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

Introduction MongoDB
Definition of
MongoDB:

 MongoDB is an open source, document-oriented database that stores data in form of


documents (Key and Value pair).
 Classified as a NoSQL Database program, MongoDB uses JSON-Like document.
 MongoDB is a learning NoSQL database.

Document Definition:

Document is same as rows and columns in RDBMS. In MongoDB documents are


called group of fields and values.

Example:

{
Name:”ABCD”,  field: value
Age:25  field:value Document
}

Collection Definition:

 A collection is a grouping of MongoDB documents.


 Documents within a collection can have different fields.
 A collection is the equivalent of a table in a Relational Database System. A
collection exists within a single database.

Example:

{
Name:”ABCD”,  field:value
Age:25  field:valueDocument
}
Collection
{
Name:”EFGH”,  field: value
Age:20  field:value Document
}

G.M.I.T Davanagere (Department of AI & ML) Page 19


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

1. Execute the commands of MongoDB.

Show dbs / show databases

This command shows all the databases present in the


active state.

Use <database name>

This command is used to create a new database.

db

This command is used to know your current working or


selected database.

createCollection

This is used to creates the new collection


Syntax: db.createCollection(“collection name”)

Show collections

Lists all the collections in the current database.

1. db.student.insertOne({usn:1,name:”ABC”}) Insert()
To add/insert documents to the collection.
Syntax:
2. db.student.insertMany([ 1. db.collection_name.insertOne({key:”value”})inserti
{usn:1,name:”ABC”}, ng only 1 document.
{usn:2,name:”GHI”} 2. db.collection_name.insertMany([{key:”value”},{
]) key:”value”}])inserting more than 1 documents at a
time.

G.M.I.T Davanagere (Department of AI & ML) Page 20


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)
1. db.student.deleteOne({usn:1}) Delete
2. db.student.deleteMany({usn:5}) This command is used to delete any one or more
documents.
Syntax:
1. db.collection_name.deleteOne({condition})
2. db.collection_name.deleteMany({condition}
)
Syntax: Drop Collection: To drop the selected collection.
db.collection_name.drop()

db.dropDatabase() Drop database: This command is used to drop the


current database.

Syntax: Find()
db.collection_name.find() This function is used to show all documents in a
collection.

Syntax: Update: Update the single document.


db.collection_name.updateOne({condition},
{operator}:{field:value})

Syntax: Update: Update the multiple documents.


db.collection_name.updateMany({condition},
{operator}:{field:value})

Syntax: Replace: Replace the complete one document.


db.collection_name.replaceOne({condition},
{operator}:{field:value})

G.M.I.T Davanagere (Department of AI & ML) Page 21


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

Lab Experiments
1 a. Execute the commands of MongoDB and operations in MongoDB: Insert, Query,
Update, Delete and Projection. (Note: Use any Collection) or Execute MongoDB basic
Queries using CRUD operations (Create, Read, Update, Delete)

Emp_No Ename JOB Manager_NO Salary Commission


1 John Doe Manager 1 50000 850
2 Jane Smith Developer 2 40000 500
3 Alice Johnson Analyst 3 35000 360
4 David Designer 1 65000 900
5 Andrew Davidson Administrator 3 80000 1000

Execute the Below Queries Based on above Given Documents.

 Create a new DATABASE in yours name “---------“


 Create a COLLECTION name called “EMPLOYEE”.
 Insert all the above given Documents to EMPLOYEE Collection.
 Read all the Documents in a EMPLOYEE collection.
 Update the JOB Analyst to CODE WRITER for Ename Alice Johnson.
 Delete the Emp_NO having 4 Document.

Result:

 Create a new DATABASE in yours name “---------“

 Create a COLLECTION name called “EMPLOYEE”.

G.M.I.T Davanagere (Department of AI & ML) Page 22


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

 Insert all the above given Documents to EMPLOYEE Collection.

 In MongoDB after inserting the documents to the


collection automatically generated object ID this ID
is unique for every record.
 This ID having 12 bytes and it is in the form of
BSON format (Binary Encoded JSon).

G.M.I.T Davanagere (Department of AI & ML) Page 23


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

 Read all the Documents in a EMPLOYEE collection.

 Update the JOB Analyst to CODE WRITER for Ename Alice Johnson.

G.M.I.T Davanagere (Department of AI & ML) Page 24


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

Read the Documents to check the Updates.

Here JOB is
Updated from
Analyst to
CODE WRITER

G.M.I.T Davanagere (Department of AI & ML) Page 25


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)
 Delete the Emp_NO having 4 Document.

Read the Documents to check the document is Deleted or Not.

Here Deleted the


Document
Emp_No having 4

G.M.I.T Davanagere (Department of AI & ML) Page 26


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)
Experiment 2

a. Develop a MongoDB query to select certain fields and ignore some fields of the
documents from any collection.
b. Develop a MongoDB query to display the first 5 documents from the results
obtained in a collection [use of limit and find].

Limit Definition:

In MongoDB the limit() method limits the number of documents that you want.
It basically defines the maximum limit of documents that you want. In this method we only
pass numeric values. Passing 0 in the method(limit(0)) is equivalent to no limit.

Syntax:
db.collection_name.find(<query>).limit(<numeric value>)

Example:

db.EMPLOYEE.find().limit(1) // this sentence display only 1st document from the


EMPLOYEE collection.

Skip Definition:
In MongoDB skip() method will skip the first N documents from the query
result, you just need to pass the number of documents to be skipped.
It basically removes the first n documents from the result set.

Syntax:
db.collection_name.find(<query>).skip(<offset/numeric value>)

Example:

db.EMPLOYEE.find().skip(2) //this query ignore the first 2 documents from the


EMPLOYEE collection and display remaining documents from the collection..

Insert the below documents to the “EMPLOYEE” collection.


Emp_No Ename JOB Manager_NO Salary Commission
5 David Designer 1 65000 900
6 Luis Stonely Senior HR 2 76000 450
7 Sammy Stanmore Receptionist 4 15000 150
8 George Floyd IT admin 5 25000 200

( :~ Lab first experiment using EMPLOYEE collection. here also use same collection continue
insert above documents to the previous collection “EMPLOYEE” )

G.M.I.T Davanagere (Department of AI & ML) Page 27


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

Queries

1. Develop a MongoDB query to select Emp_No, Ename and ignore remaining fields of
the documents from the EMPLOYEE collection.
2. Develop a MongoDB query to select Ename and JOB fields without _Id for
all documents from the EMPLOYEE collection.
3. Execute a MongoDB query to display the first 5 Documents from the results obtained
in an EMPLOYEE collection (use limit and find).
4. Develop a MongoDB query to ignore the first 3 documents from the EMPLOYEE
collection and display only 4th and 5th documents from the EMPLOYEE collection.
5. Execute a query to ignore starting 5 documents from the Employee collection.
6. Develop a MongoDB query for replace the Ename:”George Floyd” document to….

Emp_No Ename JOB Manager_NO Salary Commission


9 Bhaskar Engineer 10 100000 1500

G.M.I.T Davanagere (Department of AI & ML) Page 28


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

Insert the below documents to the “EMPLOYEE” collection.


Emp_No Ename JOB Manager_NO Salary Commission
5 David Designer 1 65000 900
6 Luis Stonely Senior HR 2 76000 450
7 Sammy Stanmore Receptionist 4 15000 150
8 George Floyd IT admin 5 25000 200

G.M.I.T Davanagere (Department of AI & ML) Page 29


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

Queries Out Put


1. Develop a MongoDB query to select Emp_No, Ename and ignore remaining fields of
the documents from the EMPLOYEE collection.

G.M.I.T Davanagere (Department of AI & ML) Page 30


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

2. Develop a MongoDB query to select Ename and JOB fields without _Id for
all documents from the EMPLOYEE collection.

G.M.I.T Davanagere (Department of AI & ML) Page 31


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

3. Execute a MongoDB query to display the first 5 Documents from the results
obtained in a EMPLOYEE collection (use limit and find).

G.M.I.T Davanagere (Department of AI & ML) Page 32


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

4. Develop a MongoDB query to ignore the first 3 documents from the EMPLOYEE
collection and display only 4th and 5th documents from the EMPLOYEE collection.

G.M.I.T Davanagere (Department of AI & ML) Page 33


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

5. Execute a query to ignore starting 5 documents from the Employee collection.

G.M.I.T Davanagere (Department of AI & ML) Page 34


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

6. Develop a MongoDB query for replace the Ename:”George Floyd” document to….

Emp_No Ename JOB Manager_NO Salary Commission


9 Bhaskar Engineer 10 100000 1500

G.M.I.T Davanagere (Department of AI & ML) Page 35


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)
Read the Documents

Here document is
replaced but ID is same.

G.M.I.T Davanagere (Department of AI & ML) Page 36


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)
Experiment 3:

a. Execute query selectors (Comparison selectors, Logical selectors) and list out the
results on any Collection.
b. Execute query selectors (Geospatial selectors, Bitwise selectors) and list out the
results on any Collection.

Comparison Selectors (Comparison Operators)

Comparison query operators in MongoDB are used to filter documents based on some
specific criteria within their fields.

MongoDB uses various comparison query operators to compare the values of the documents.
The following table contains the comparison query operators.

Operator Description
$eq Matches the values of the fields that are equal to a specified value.
$ne Matches all values of the field that are not equal to a specified value.
$gt Matches values of the fields that are greater than a specified value.
$gte Matches values of the fields that are greater than or equal to the specified
value.
$lt Matches values of the fields that are less than a specified value.
$lte Matches values of the fields that are less than or equal to the specified value.
$in Matches any of the values specified in an array.
$nin Matches none of the values specified in an array.

Logical Selectors ( Logical Operators)

Logical operators return data based on expressions that evaluate to true or false.

The following table contains the comparison query operators.

Operator Description
$and Joins query clauses with a logical AND returns all documents that match the
conditions of both clauses.
$not Inverts the effect of a query expression and returns documents that do not
match the query expression.
$nor Joins query clauses with a logical NOR returns all documents that fail to
match both clauses.
$or Joins query clauses with a logical OR returns all documents that match the
conditions of their clauses.

G.M.I.T Davanagere (Department of AI & ML) Page 37


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

Bitwise selectors (Bitwise Operators)

The $bit operator performs a bitwise update of a field. The operator supports bitwise and,
bitwise or and bitwise xor (i.e. exclusive or) operations. To specify a $bit operator
expression, use the following prototype: {$bit :{< field> :{< and\or\xor:<int>}}}.

G.M.I.T Davanagere (Department of AI & ML) Page 38


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

Create STUDENT collection and Insert the below Documents to the STUDENT collection
and Perform the Above operations.

Sl_No USN NAME BRANCH SEMESTER CGPA


1 4BD21AI090 Prajwal AIML 6 9
2 4BD20CS100 Rashmi CS 4 8
3 4BD21AI010 Sagar AIML 6 7.2
4 4BD21IS017 Sandesh IS 6 9
5 4BD19IS100 Priya IS 8 9.5

Queries

1. Apply Comparison operators for the following queries using above student
collection Documents :~

1. Display all the students having the CGPA equal to 9.5.


2. Display all the students who have the CGPA not equal 9.
3. Display all the students with CGPA less than 9.
4. Display all the students with CGPA less than or equal 8.
5. Display all the students who have the CGPA greater than 9.
6. Display all the students who have the CGPA greater than or equal 9.
7. Display all the students with CGPA greater than 7.2 , but less than 9.
8. Display students details of 3, 4, 5 Sl_No.
9. Display all the students details except 4, 5 Sl_No.
10. Display all the Distinct Branches from the STUDENT collection.
11. Display the number of students in IS Branch.

2. Apply Logical operators for following queries:~

1. Display all the students in IS and in 6th SEMESTER.


2. Display all the students in AIML or 6th SEMESTER.
3. List the students who are not in the 6th SEMESTER.

3. Apply Bitwise operators (and, or, not, nor):~

1. Update the SEMESTER 6 to 5 using bitwise AND operator for Sl_No 4 (Check
the result SEMESTER:6 is updated to 4).
2. Update the CGPA 8 to 2 using bitwise OR operator for Sl_No 2 (Check the result
CGPA for Sl_No:2 is updated to 10).
3. Update the SEMESTER 8 to 4 using bitwise XOR operator for Sl_No 5 (Check
the result SEMESTER:8 is updated to 12).

G.M.I.T Davanagere (Department of AI & ML) Page 39


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

Create STUDENT collection and Insert below Documents to collection.

Sl_No USN NAME BRANCH SEMESTER CGPA


1 4BD21AI090 Prajwal AIML 6 9
2 4BD20CS100 Rashmi CS 4 8
3 4BD21AI010 Sagar AIML 6 7.2
4 4BD21IS017 Sandesh IS 6 9
5 4BD19IS100 Priya IS 8 9.5

Inserting the Documents to the STUDENT collection.

G.M.I.T Davanagere (Department of AI & ML) Page 40


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

ID generated for every Document.

Retrieve the STUDENT collection.

G.M.I.T Davanagere (Department of AI & ML) Page 41


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

1. COMPARISON Operators Queries………

Q1. Display all the students having the CGPA equal to 9.5.

Q2. Display all the students who have the CGPA not equal 9.

G.M.I.T Davanagere (Department of AI & ML) Page 42


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

Q3. Display all the students with CGPA less than 9.

Q4. Display all the students with CGPA less than or equal 8.

G.M.I.T Davanagere (Department of AI & ML) Page 43


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

Q5. Display all the students who have the CGPA greater than 9.

Q6. Display all the students who have the CGPA greater than or equal 9.

G.M.I.T Davanagere (Department of AI & ML) Page 44


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

Q7. Display all the students with CGPA greater than 7.2 but less than 9.

Q8. Display student’s details of Sl_No 3, 4, 5.

G.M.I.T Davanagere (Department of AI & ML) Page 45


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

Q9. Display all the students details except 4, 5 Sl_No.

Q10. Display all the Distinct Branches from the STUDENT collection.

Q11. Display the number of students in IS Branch.

G.M.I.T Davanagere (Department of AI & ML) Page 46


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)
2. LOGICAL Operators Queries…………….

Q1. Display all the students in IS and in 6th sem.

Q2. Display all the students in AIML or 6th sem.

G.M.I.T Davanagere (Department of AI & ML) Page 47


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

Q3. List the students who are not in the 6th SEMESTER.

G.M.I.T Davanagere (Department of AI & ML) Page 48


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

3. Bitwise Operators Queries……………….

Q1. Update the SEMESTER 6 to 5 using bitwise AND operator for Sl_No 4 (Check the
result SEMESTER: 6 is updated to 4).

Check the Result it is updated or not…

Before updating… After updated

Observe the SEMESTER is updated from 6 to 4. 0110 Binary conversion of 6.


0101 Binary conversion of 5.

0100 Binary conversion of 4.

G.M.I.T Davanagere (Department of AI & ML) Page 49


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

Q2. Update the CGPA 8 to 2 using bitwise OR operator for Sl_No 2 (Check the result CGPA
for Sl_No:2 is updated to 10).

Check the result is updated or not..

Before Updating….. After Updated……..

Initially CGPA 8 the binary value of 8 is 1000, Updating CGPA is 2 the binary value of 2 is
0010.

1000
0010

1010 The Decimal value of 1010 is 10. So CGPA is updated to 10.

G.M.I.T Davanagere (Department of AI & ML) Page 50


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

Q3. Update the SEMESTER 8 to 4 using bitwise XOR operator for Sl_No 5 (Check the
result SEMESTER:8 is updated to 12).

Check the result is updated or not..

Before Updating……….. After Updated

Initially SEMESTER 8 the binary value of 8 is 1000, Updating SEMESTER is 4 the binary
value of 4 is 0100.

1000
0100
The Decimal value of 1100 is 12. So SEMESTER is updated to 12.
1100

G.M.I.T Davanagere (Department of AI & ML) Page 51


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

Create a BITWISE collection and Insert below documents to the collection.

Name Value
SANDESH 5
Pratham 7
Harika 6
Niharika 4

Displaying all Documents

G.M.I.T Davanagere (Department of AI & ML) Page 52


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

1. $bitAllSet: (Find documents where all bits are set)


Find values where the binary status has both the 0,1st bits set.

5 7 6 4
0101 0111 0110 0100 Perform AND operation
1111 1111 1111 1111 AllBitsSet
After getting the results we
0101 0111 0110 0100 Mentioned bitsAllSet 0th and 1st
both will available only in the 7 so
That is Display.
321 0 Positions

2. $bitsAnySet (Find documents where any of the bits are set)


Find values where the binary status has at least the 0th bits set.

5 7 6 4
0101 0111 0110 0100 Perform AND operation
0001 0001 0001 0001 BitsAnySet
After getting the results we
0001 0001 0000 0000 Mentioned bitsAnySet 0th a
will available only in the 5th ,1st so
That is Display.
321 0 Positions

G.M.I.T Davanagere (Department of AI & ML) Page 53


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

3. $bitsAllClear (Find documents where all bits are clear)


Find values where the binary status has both the 1st and 3rd bits clear.

5 7 6 4
0101 0111 0110 0100 Perform OR operation
0000 0000 0000 0000 BitsAllClear
After getting the results we
0101 0111 0110 0100 Mentioned bitsAllClear 1st and
3rd bit will 0 available only in the
5 and 4 ..That is Display.
Positions

4. $bitsAnyClear (Find documents where any of the bits are clear)


Find values where the binary status has atleast the 1st bit is clear.

5 7 6 4
0101 0111 0110 0100 Perrform AND operation
0010 0010 0010 0010 BitsAnyClear
After getting the results we
0000 0010 0010 0000 Mentioned bitsAnySet 1st bit
will available only in the 5th ,4st so
That is Display.Positions

G.M.I.T Davanagere (Department of AI & ML) Page 54


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

IV. GeoSpatial Selectors: Geospatial operations return data based on geospatial


expression condition.

Name Description
$geoWithin Selects geometries within a bounding GeoJSON geometry. The 2dsphere and
2d indexes support $geoWithin.
$near Returns geospatial objects in proximity to a point. Requires a geospatial index.
The 2dshere and 2d indexes support $near.
$geometry Specifies a geometry in GeoJSON format to geospatial query operators.
$maxDistance Specifies a maximum distance to limit the results og $near and $nearSphere
queries. The 2dSphere and 2d indexes support $maxDistance.
$minDistance Specifies a miniimum distance to limit the results og $near and $nearSphere
queries. The 2dSphere and 2d indexes support $minDistance.
$Polygon Specifies a POLYGON to using legacy coordinates pairsfor $geoWithin
queries. The 2d index support $center.

Insert:

G.M.I.T Davanagere (Department of AI & ML) Page 55


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

Display:

Create an Index for Location field with 2dsphere.

G.M.I.T Davanagere (Department of AI & ML) Page 56


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

1. $near:
Nearest Location for given coordinates with maxDistance and minDistance.

2. GeoWithin:

G.M.I.T Davanagere (Department of AI & ML) Page 57


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

Experiment No: 4
Create and demonstrate how projection operators ($, $eleMatch and $slice) would be used in
the MongoDB.

Introduction about Projection Operators in MongoDB:

MongoDB query and projection operators allow users to control queries and results. Query
operators help to filter data based on specific conditions. Example: ~ $eq, $and, $exists, etc.

Projection operators in Mongo DB control which fields should be shown in the results.
Example: ~ $slice, $, $meta, $eleMatch.

Operator Description
$ The positional $ operator limits the contents of an <array> to return the
first element that matches the query condition on the array.
$slice Limits the number of elements projected from an array. Supports skip
and limit slices.
$meta Returns the metadata associated with a document, e.g. “textScore” when
performing text search.
Syntax:
{$meta:<metaDatakeyword>}
$eleMatch The $eleMatch operator limits the contents of an <array> field from the
query results to contain only the first element matching the $eleMatch
condition.

1. Create a PRODUCTS collection.


2. Insert the below documents to the PRODUCTS collection and Execute the given
queries using Projection Operators.

Name Brand Features Reviews


name value user rating comment
processor Intel i7 Alice 5 Excellent
Laptop BrandA RAM 16GB BOB 4 Very Good
storage 512 GB SSD Charlie 3 Average
Processor Snap dragon 888 Dave 4 Good phone
Smartphone BrandB RAM 8GB Eve 2 Not satisfied
Storage 256 GB

G.M.I.T Davanagere (Department of AI & ML) Page 58


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)
Queries:

1. Find the product names “Laptop” and project the review from the user “Alice”.
2. Find the product named “Laptop” and project the review where the rating is
greater than 4.
3. Find the product named “Smartphone” and project the first review.
4. Find the product named “Laptop” and project the name, the first two features and
the review with the highest rating.

Creating PRODUCTS collection.

Inserting given Documents to the PRODUCTS collection.

G.M.I.T Davanagere (Department of AI & ML) Page 59


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

Retrieve the all the Documents from the PRODUCTS collection.

G.M.I.T Davanagere (Department of AI & ML) Page 60


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

Execute Queries

1. Find the product names “Laptop” and project the review from the user “Alice”.

2. Find the product named “Laptop” and project the review where the rating is greater
than 4.

 The $ operator is useful for projecting the first matching element from an array.
 The $elemMatch operator allows you to project the first array element that
matches specified criteria.

G.M.I.T Davanagere (Department of AI & ML) Page 61


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

3. Find the product named “Smartphone” and project the first review.

4. Find the product named “Laptop” and project the name, the first two features and the
review with the highest rating.

G.M.I.T Davanagere (Department of AI & ML) Page 62


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

Experiment 5

Execute Aggregation operations ($avg, $min, $max, $push, $addToSet etc.). students
encourage to execute several queries to demonstrate various aggregation operators)
[Refer: Book 3 Chapter 15]

Definition of Aggregate Operators: Aggregation Operations process data records and return
computed results. Not only do we have the ability to aggregate data on the client side with
Javascript, but we can use MongoDB to run operations on the server against out collections
stored in the database before the result is returned to the client.

Operator Description
$avg Returns the average value of the numeric values. $avg ignores non-numeric
values.
$min Returns the minimum value. $min compares both value and type, using
the specified BSON comparison order for values of different types.
$max Returns the maximum value. $max compares both value and type, using
the specified BSON comparison order for values of different types.
$push The $push operator appends a specified value to an array.
$addToSet The $addToSet operator adds a value to an array unless the value is already
present, in which case $addToSet does nothing to that array.
$group The $group stage separates documents into groups according to a "group
key". The output is one document for each unique group key. A group key
is often a field, or group of fields. The group key can also be the result of an
expression.

Create SALES collection and insert the below documents to the SALES collection and
execute some Aggregation Operations.

Date Product Price Quantity Customer


new Date Laptop 1200 1 Amar
(“2024-01-01”)
new Date Laptop 1200 2 Babu
(“2024-01-01”)
new Date Mouse 250 5 Chandru
(“2024-01-01”)
new Date Key Board 450 3 Amar
(“2024-01-01”)
new Date Monitor 300 1 Babu
(“2024-01-01”)
new Date Laptop 1200 1 Deva
(“2024-01-01”)

G.M.I.T Davanagere (Department of AI & ML) Page 63


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

Create SALES Collection

Insert the Above Documents to SALES collection

G.M.I.T Davanagere (Department of AI & ML) Page 64


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

Retrieve all the Documents from the SALES collection.

G.M.I.T Davanagere (Department of AI & ML) Page 65


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

Q1. Calculate the average price of each products.

Query:

Out Put

Q2. Find the Minimum Price of each Product.

Query:

Out Put:

G.M.I.T Davanagere (Department of AI & ML) Page 66


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

Q3. Find the Maximum Price of each Products.

Query:

Out Put:

Q4. Group sales by customers and push each purchased product into an array.

Query:

Out Put:

G.M.I.T Davanagere (Department of AI & ML) Page 67


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

Q5. Group sales by customer and add each unique purchased product to an array.

Query:

Out Put:

Q6. Calculate the total quantity and total sales amount for each product, and list all
customers who purchased each product.

G.M.I.T Davanagere (Department of AI & ML) Page 68


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

Experiment 6

Execute Aggregation Pipeline and its operations (pipeline must contain $match, $group,
$sort, $project, $skip etc. students encourage executing several queries to demonstrate
various aggregation operators) [refer book 2: chapter 6]

1. Create “RESTAURANTS” collection.


2. Insert the below documents “RESTAURANTS” collection.

Name Cuisine Location Reviews


User Rating Comment
Biriyani Indian Jayanagara Aarav 5 Amazing Biriyani
House Bhavana 4 Great Place!
Burger Joint American Koramanagal Chirag 3 Average Burger
Devika 4 Good Value
Pasta House Italian Rajaji Nagar Esha 5 Delicious Pasta
Farhan 4 Nice Ambience
Curry Palace Indian Jayanagara Gaurav 4 Spicy and Tasty
Harini 5 Best Curry in Town
Taco Stand Mexican Jayanagara Ishan 5 Fantastic Tacos!
Jaya 4 Very Authentic

Execute Below Queries.

1. Filter/Match the Restaurants by cuisine(“Jayanagara” Location)


2. Deconstruct the “Reviews” array from each documents to output a documents for
each review.
3. Group the documents by Restaurants name and calculate the average rating and total
number of reviews.
4. Sort the results by average rating in Ascending order.
5. Display only first 2 documents from the RESTAURANTS collection.
6. Display the last 3 documents from the RESTAURANTS collection.
7. Project the output to include only the Restaurants name, avg rating and total reviews.
8. Filter restaurants by cuisine(“Jayanagara” Location), Deconstruct the reviews array
from each documents to output a document for review, group the documents by
restaurants name and calculate the Avg_Rating and Total_Reviews, sort the results by
avg rating in ascending order, Restructure the output to include only the restaurants
Name, Avg_Rating and Total_Reviews and skip the first document.
Creating the “RESTAURANTS” collection.

G.M.I.T Davanagere (Department of AI & ML) Page 69


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

OUT PUT

Inserting Documents.

G.M.I.T Davanagere (Department of AI & ML) Page 70


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

Retrieve/Display all the documents from the “RESTAURANTS” collection.

G.M.I.T Davanagere (Department of AI & ML) Page 71


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

Q1. Filter/Match the Restaurants by cuisine(“Jayanagara” Location).

G.M.I.T Davanagere (Department of AI & ML) Page 72


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

Q2. Deconstruct the “Reviews” array from each documents to output a documents for each
review.

G.M.I.T Davanagere (Department of AI & ML) Page 73


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)
Countinue……

Q3. Group the documents by Restaurants name and calculate the average rating and total
number of reviews.

G.M.I.T Davanagere (Department of AI & ML) Page 74


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

Q4. Sort the results by Avg_Rating in Ascending order.

Sort the results by Avg_Rating in Descending order.

G.M.I.T Davanagere (Department of AI & ML) Page 75


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

Q5. Display only first 2 documents from the RESTAURANTS collection.

Q6 Display only last 3 documents from the RESTAURANTS collection.

G.M.I.T Davanagere (Department of AI & ML) Page 76


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

Q7. Project the output to include only the Restaurants name, avg rating and total reviews.

Q8. Deconstruct the reviews array from each documents to output a document for review,
group the documents by restaurants name and calculate the Avg_Rating and Total_Reviews,
sort the results by avg rating in ascending order, Restructure the output to include only the
restaurants Name, Avg_Rating and Total_Reviews and skip the first document.

G.M.I.T Davanagere (Department of AI & ML) Page 77


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

Experiment 7

a. Find all listings with listing_url, name, address, host_picture_url in the listings
And Reviews collection that have a host with a picture URL.
b. Using E-commerce collection write a query to display reviews summary.

A. Create “Listing_URL” collection


Insert all below given Documents to “Listing_URL” collection.

Listing_URL Name Address Host


Street Suburb City Country Name Picture_Url

http://www.exa 123 Wonder http://www.example.com


mple.com//listin Beautiful Main Central Metropolis Land Alice //images//host123.jpg
g/123456 Apartment
Street
Cozy
http://www.exa Cottage 456 Wonder
mple.com//listin Another North Small Ville Land BOB
g//654321 St

http://www.exa Modern 789 Wonder Charlie http://www.example.com


mple.com//listin Condo Side East Gotham Land //images//host789.jpg
g//789012 Road

Create “Listing_URL” collection.

G.M.I.T Davanagere (Department of AI & ML) Page 78


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)
Inserting Documents

Query Question

Find all listings with Listing_Url, Name, Address, Host_Picture_Url in the listings And
Reviews collection that have a host with a picture URL.

Input Query

G.M.I.T Davanagere (Department of AI & ML) Page 79


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

Output Query

G.M.I.T Davanagere (Department of AI & ML) Page 80


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

B. Using E-commerce collection write a query to display reviews summary.

Product_id Name Category Price Reviews


User Rating Comment
Alice 5 Excellent
1 Laptop Electronics 1200 BOB 4 Very Good
Charlie 3 Average
Dave 4 Good Phone
2 Smart Phone Electronics 800 Eve 2 Not Satisfied
Frank 5 Amazing
Grace 5 Great Sound
3 Head Phone Accessories 150 Heidi 3 Okay

Create Collection:

Insert:

G.M.I.T Davanagere (Department of AI & ML) Page 81


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

Query Question

Deconstruct the Reviews array from each documents, group the documents by Product Name
and calculate the Total_Reviews, Avg_Rating and push the comments to array then project
the Output document to include Product Name, Total_Reviews, Avg_Rating and Comments.

Input Query:

Output

G.M.I.T Davanagere (Department of AI & ML) Page 82


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

Experiment 9

a. Develop a query to demonstrate Text search using catalog data collection for a given
word.
b. Develop queries to illustrate excluding documents with certain words and phrases.
[Refer: Book 2: Chapter 9]

Create an CSV file for MOVIES database and import that database in mongodb command
prompt then Create an text search index and search a word and search phrase .

Name Year Duration Rating Type Language


Raju Kannada Medium 2018 159 mins 7.2 Comedy,Drama Kannada
Jaga Mecchida Maga 1972 153 mins 8.2 Drama Kannada
Raktha Gulabhi 2021 132 mins 9.4 Crime Kannada
Laddu 2021 127 mins 8.6 Comedy,Romance Kannada
Rajannana Maga 2018 143 mins 7.8 Action Kannada
Thayige Thakka Maga 2018 147 mins 5.4 Drama Kannada
First Rank Raju 2015 148 mins 7.6 Comedy,Drama Kannada
Daari Thappida Maga 1975 138 min 7.8 Crime,Drama Kannada
Bhoothayyana Maga Ayyu 1974 156 mins 8.3 Drama Kannada
Thandege Thakka Maga 2013 139 mins 7.1 Drama Kannada

Import above MOVIE database with MOVIE Collection with CSV file

 Connect mongod to mongosh

G.M.I.T Davanagere (Department of AI & ML) Page 83


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

 Display the Databases

 Use MOVIE database and display collections in the


MOVIE database

 Show Collections

 Count the documents when importing time.

G.M.I.T Davanagere (Department of AI & ML) Page 84


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

 Display all documents available in MOVIES collection

G.M.I.T Davanagere (Department of AI & ML) Page 85


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

 Create an text index for the word Name and Type fields for text search

 Now, let’s perform a text search to find documents containing a specific word. For
example, let’s search the word “Maga”.

G.M.I.T Davanagere (Department of AI & ML) Page 86


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)
 Perform a text search query to find documents containing the word “Raju”.

 Perform a Text search query for a phrase: Now, let’s perform a text search to find
documents containing a specific phrase. For example, let’s search for the phrase
“Raktha Gulabi”.

G.M.I.T Davanagere (Department of AI & ML) Page 87


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

 Exclude Documents Containing the word “Action”.


 Suppose we want to list movies that belong to Crime or Romance (or both) Type but
not belonging to the Action Type movies.

G.M.I.T Davanagere (Department of AI & ML) Page 88


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

Experiment 10

Develop an aggregation pipeline to illustrate Text search on Catalog data collection.


[Refer: Book 2: Chapter 9]

Create a CATALOG collection and insert the below documents to collection and perform the
AGGREGATE PIPELINE operations.
Name Description Category Year Price Rating
The Great A classic novel written by F. Books 1925 4000 5
Gatsby Scott Fitzgerald
Introduction A Comprehensive Textbook on Books 2018 800 9
to Algorithm Algorithm and Data Structures
Harry Potter A Fantasy novel written by J.K Books 1940 4500 8
and the Rowling
spacers Stone
Samsung A High end Smart Phone and Electronics 2022 30000 8
Galaxy S21 powerful Features
Apple The latest iPhone model with Electronics 2024 100000 6
iPhone 13 improved camera

G.M.I.T Davanagere (Department of AI & ML) Page 89


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)
Group the catalog by CATEGORY and calculate the average rating and push the year into
array

Group the catalog by CATEGORY and calculate the average rating and sort the
Average rating in Descending order

G.M.I.T Davanagere (Department of AI & ML) Page 90


SHIVARANJANI S.S, Assistant Professor
MongoDB
(BDSL456B)

Take RESULT variable perform given query and store the result into the RESULT
variable then print result using printjson function.

Group the catalog by CATEGORY and calculate the average rating, push the year
into array and sort the Average rating in Descending order project category, Average Rating
and push year only for first document.

G.M.I.T Davanagere (Department of AI & ML) Page 91


SHIVARANJANI S.S, Assistant Professor

You might also like