Mangodb v1 Manual
Mangodb v1 Manual
(BDSL456B)
4. Scroll Down
Choose 7.0.9(current), Windows 64,msi
6. Click on Save
8. MongoDB Compass
Installation: Double click on this
9. Click on Next.
10. Click on I accept the terms in the license agreement and press next.
13. Select Run service as Network Service user and Click Next Button.
17. Wait…
2. Scroll Download
Select Version: 2.2.5
Platform: Windows X64( 10+)
Package: Zip
Click On Download Button
8. MongoDB---->Server
9. Server---->7.0
10. 7.0---->Bin
Open Command Prompt and Type CD (Change the Working Directory) and
Paste the Above Copied Path.
5. Open Data Folder and Cretae One more Folder within the Data Folder.
6. Data Folder--->New Folder--->Rename New Folder to db.
Introduction MongoDB
Definition of
MongoDB:
Document Definition:
Example:
{
Name:”ABCD”, field: value
Age:25 field:value Document
}
Collection Definition:
Example:
{
Name:”ABCD”, field:value
Age:25 field:valueDocument
}
Collection
{
Name:”EFGH”, field: value
Age:20 field:value Document
}
db
createCollection
Show collections
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.
Syntax: Find()
db.collection_name.find() This function is used to show all documents in a
collection.
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)
Result:
Update the JOB Analyst to CODE WRITER for Ename Alice Johnson.
Here JOB is
Updated from
Analyst to
CODE WRITER
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:
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:
( :~ Lab first experiment using EMPLOYEE collection. here also use same collection continue
insert above documents to the previous collection “EMPLOYEE” )
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….
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 a 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.
6. Develop a MongoDB query for replace the Ename:”George Floyd” document to….
Here document is
replaced but ID is same.
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 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 operators return data based on expressions that evaluate to true or false.
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.
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>}}}.
Create STUDENT collection and Insert the below Documents to the STUDENT collection
and Perform the Above operations.
Queries
1. Apply Comparison operators for the following queries using above student
collection Documents :~
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).
Q1. Display all the students having the CGPA equal to 9.5.
Q2. Display all the students who have the CGPA not equal 9.
Q4. Display all the students with CGPA less than or equal 8.
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.
Q7. Display all the students with CGPA greater than 7.2 but less than 9.
Q10. Display all the Distinct Branches from the STUDENT collection.
Q3. List the students who are not in the 6th SEMESTER.
Q1. Update the SEMESTER 6 to 5 using bitwise AND operator for Sl_No 4 (Check the
result SEMESTER: 6 is updated to 4).
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).
Initially CGPA 8 the binary value of 8 is 1000, Updating CGPA is 2 the binary value of 2 is
0010.
1000
0010
Q3. Update the SEMESTER 8 to 4 using bitwise XOR operator for Sl_No 5 (Check the
result SEMESTER:8 is updated to 12).
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
Name Value
SANDESH 5
Pratham 7
Harika 6
Niharika 4
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
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
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
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
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:
Display:
1. $near:
Nearest Location for given coordinates with maxDistance and minDistance.
2. GeoWithin:
Experiment No: 4
Create and demonstrate how projection operators ($, $eleMatch and $slice) would be used in
the 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. 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.
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.
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.
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.
Query:
Out Put
Query:
Out Put:
Query:
Out Put:
Q4. Group sales by customers and push each purchased product into an array.
Query:
Out Put:
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.
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]
OUT PUT
Inserting Documents.
Q2. Deconstruct the “Reviews” array from each documents to output a documents for each
review.
Q3. Group the documents by Restaurants name and calculate the average rating and total
number of reviews.
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.
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.
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
Output Query
Create Collection:
Insert:
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
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 .
Import above MOVIE database with MOVIE Collection with CSV file
Show Collections
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”.
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”.
Experiment 10
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
Group the catalog by CATEGORY and calculate the average rating and sort the
Average rating in Descending order
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.