0% found this document useful (0 votes)
52 views50 pages

Mongo DB

MongoDB is a document-oriented, cross-platform database that offers high performance, availability, and scalability, utilizing collections and documents without enforcing a schema. It supports various data types and provides powerful CRUD operations, allowing for dynamic queries and easy data manipulation. Key advantages include schema-less design, ease of scaling, and rich query capabilities, making it suitable for modern applications.

Uploaded by

shiva
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)
52 views50 pages

Mongo DB

MongoDB is a document-oriented, cross-platform database that offers high performance, availability, and scalability, utilizing collections and documents without enforcing a schema. It supports various data types and provides powerful CRUD operations, allowing for dynamic queries and easy data manipulation. Key advantages include schema-less design, ease of scaling, and rich query capabilities, making it suitable for modern applications.

Uploaded by

shiva
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/ 50

MongoDB

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.
Database: Database is a physical container for collections. Each database gets its own set of files
on the file system. A single MongoDB server typically has multiple databases.

Collection: 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.

Document: 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.

The following table shows the relationship of RDBMS terminology with MongoDB

Any relational database has a typical schema design that shows number of tables and the
relationship between these tables. While in MongoDB, there is no concept of relationship.
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.
• Deep query-ability. MongoDB supports dynamic queries on documents using a document-
based query language that's nearly as powerful as SQL.
• Tuning.
• 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 (windowed) working set, enabling faster access of
data.
Why Use MongoDB?

• Document Oriented Storage: Data is stored in the form of JSON style documents.
• Index on any attribute
• Replication and high availability
• Auto-sharding
• Rich queries
• Fast in-place updates
• Professional support by MongoDB

MongoDB Datatypes

MongoDB supports many datatypes. Some of them are:

• String: This is the most commonly used datatype to store the data. String in MongoDB
must be UTF-8 valid.
• Integer: This type is used to store a numerical value. Integer can be 32 bit or 64 bit
depending upon your server.
• Boolean: This type is used to store a boolean (true/ false) value.
• Double: This type is used to store floating point values.
• Min/Max Keys: This type is used to compare a value against the lowest and highest BSON
elements.
• Arrays: This type is used to store arrays or list or multiple values into one key.
• Timestamp: ctimestamp. This can be handy for recording when a document has been
modified or added.
• Object: This datatype is used for embedded documents.
• Null: This type is used to store a Null value.
• Symbol: This datatype is used identically to a string; however, it's generally reserved for
languages that use a specific symbol type.
• Date: This datatype is used to store the current date or time in UNIX time format. You can
specify your own date time by creating object of Date and passing day, month, year into it.
• Object ID: This datatype is used to store the document’s ID.
• Binary data: This datatype is used to store binary data.
• Code: This datatype is used to store JavaScript code into the document.
• Regular expression: This datatype is used to store regular expression.

Commands:

1) To create a new database or to switch to a database called “employee_db”, “use” command


is used.
➢ use employee_db
➢ Output: switched to db employee_db

Note that “use” command creates a new database, if one does not already exist.

2) To check current database, use the command “db”


➢ db
➢ Output: employee_db
3) To display all the databases, use the command “show dbs”
➢ show dbs
➢ Output: employee_db 0.124GB
local 0.78125GB
test 0.23012GB

Note that to display database, you need to insert at least one document into it.

In MongoDB default database is test. If you didn't create any database, then collections

will be stored in test database.

4) To drop existing database, use “db.dropDatabase()” command. This will delete the
selected database. If you have not selected any database, then it will delete default 'test'
database.
5) To create a collection called “employee_info”, db.createCollection(“Name of the
Collection”) command is used.
➢ Use test
switched to db test
➢ db.createCollection("employee_info")
{"ok": 1}

6) To check the created collections, use the command “show collections”

➢ show collections

7) To drop a collection from the database, use the command “db.collectionName.drop()”


drop () method will return true, if the selected collection is dropped successfully,
otherwise it will return false.

8) To clear the mongo shell, use the command “cls” or “Ctrl+L”

CRUD Operations

CRUD stands for basic Create, Read, Update and Delete operations using the mongo shell. These
operations create, read, update, and delete documents.
1) Create Operations: Create or insert operations add new documents to a collection. A
MongoDB database is made up of 1 or more collections which are in turn made up of 1 or more
documents. A document has a key: value structure, similar to JSON objects. If the collection does
not currently exist, insert operations will create the collection. MongoDB provides the following
methods to insert documents into a collection:

• db.collection.insertOne()

• db.collection.insertMany()

In MongoDB, insert operations target a single collection. All write operations in MongoDB
are atomic on the level of a single document.

Insert a Single Document: Collection.insertOne() inserts a single document into a collection.

Syntax: db.collection.insertOne(document)

Insert a Multiple Document: The db.<collection>.insertMany() inserts multiple documents into


a collection. It cannot insert a single document.
Syntax: db.collection.insertMany([document1, document2, ....])

Exercise 1
• Verify what database you are currently using (should be test, this is the default.) MongoDB
makes this a super easy step. From the Mongo-Shell type db and hit Enter, the output is the
current working database.
query: javascript db
• Let's create a new database called employee_db.
use employee_db
Note that use creates a new database, if one does not already exist.
• Next, let's create a collection called employee_info.
db.createCollection("employee_info")
• Let's confirm that the collection was successfully created.
show collections
Similarly, you can also use show dbs to obtain a list of the all the databases.
• Let's try to insert some data into our collection.
You are used to seeing data in a tabular format due to the relational database structure. So, let's
start with a table as seen below and then convert it into a JSON object that can be inserted into our
collection.

fname lname salary departments hiredate

john doe 70000 sales, admin 2018-08-29

Converting this table into an object, a set of key: value pairs surrounded by {} looks like this:

"fname": "john",

"lname": "doe",

"salary": 70000,

"departments": ["sales", "admin"],

"hiredate": "2018-08-29"

Now that we have our JSON object, let's insert it into our collection.

query:
db.employee_info.insertOne({

"fname": "john",

"lname": "doe",

"salary": 70000,

"departments": ["sales", "admin"],

"hiredate": "2018-08-29"})

result:

"acknowledged" : true,

"insertedId" : ObjectId("5d8e6f9ccaa4f8ddbe27296f")

The response to this query is a document in itself as seen below. "acknowldeged": true means we
the insert was successful. Also note the Object ID which is the unique identifier for this document.
Every document has its own unique _id. It is not necessary to specify _id in the query in which
case, MongoDB will automatically add one to the document.

Exercise 2

HR has sent over new employee information. Spend 5 minutes to insert the new data into
the employee_info collection.

The data is first shown in tabular format followed by JSON object format to ease you into thinking
about data non-relationally.

empno fname lname role salary departments hiredate

1 charlie rodgers manager sales, marketing


empno fname lname role salary departments hiredate

team marketing,
2 sunil chakraborty
lead finance

team
3 sally jones hr, admin
lead

4 ben bradley manager legal

5 radha desai worker

6 shruti patel worker

7 mahesh iyer manager

"empno": 1,

"fname": "charlie",

"lname": "rodgers",

"role": "manager",

"departments": ["sales", "marketing"]

},

"empno": 2,

"fname": "sunil",

"lname": "chakraborty",

"role": "team lead",

"departments": ["marketing", "finance"]

},
{

"empno": 3,

"fname": "sally",

"lname": "jones",

"role": "team lead",

"departments": ["hr", "admin"]

},

"empno": 4,

"fname": "ben",

"lname": "bradley",

"role": "manager",

"departments": ["legal"]

},

"empno": 5,

"fname": "radha",

"lname": "desai",

"role": "worker"

},

"empno": 6,

"fname": "shruti",
"lname": "patel",

"role": "worker"

},

"empno": 7,

"fname": "mahesh",

"lname": "iyer",

"role": "manager"

Insert Multiple Documents: Collection.insertMany() can insert multiple documents into a


collection. Pass an array of documents to the method.

query:

db.employee_info.insertMany([
{
"empno": 1,
"fname": "charlie",
"lname": "rodgers",
"role": "manager",
"departments": ["sales", "marketing"]
},
{
"empno": 2,
"fname": "sunil",
"lname": "chakraborty",
"role": "team lead",
"departments": ["marketing", "finance"]
},
{"empno": 3,
"fname": "sally",
"lname": "jones",
"role": "team lead",
"departments": ["hr", "admin"]
},
{
"empno": 4,
"fname": "ben",
"lname": "bradley",
"role": "manager",
"departments": ["legal"]
},
{
"empno": 5,
"fname": "radha",
"lname": "desai",
"role": "worker"
},
{
"empno": 6,
"fname": "shruti",
"lname": "patel",
"role": "worker"
},
{
"empno": 7,
"fname": "mahesh",
"lname": "iyer",
"role": "manager"
}
])

Exercise 3

You've got some more interesting employees! Spend 10 minutes converting the following table
to JSON and inserting it into our employee_info collection.

name title interesting fact address

Harry Hogwarts
Wizard I kicked the shot out of Voldemort!
Potter castle

I can only say 3 words in this order: 'I am


Groot Superhero Planet X
Groot'!

Electric type Want to see my ThuderBolt and Quick


Pikachu Pallet Town
pokemon Attack?!

2) Read Operations: Read operations retrieve documents from a collection; i.e. query a collection
for documents. MongoDB provides the following methods to read documents from a collection:

• db.collection.find()

• db.collection.findOne()

You can specify query filters or criteria that identify the documents to return.
Query - It specifies the selection criteria for the documents to be retrieved. It is an object that
contains one or more key-value pairs, where each key represents a field in the document and the
value represents the value to match for that field.

Projection - It specifies which fields to include or exclude in the result set. It is an object that
contains one or more key-value pairs, where each key represents a field in the document and the
value represents whether to include (1) or exclude (0) the field in the result set.

Note: Both query and projection are optional.

Note: pretty() method is used to decorate the result such that it is easy to read.

Query Selectors:

Comparison: Comparison operators return data based on value comparisons.

Name Description

$eq Matches values that are equal to a specified value.

$gt Matches values that are greater than a specified value.

$gte Matches values that are greater than or equal to a specified value.

$in Matches any of the values specified in an array.

$lt Matches values that are less than a specified value.

$lte Matches values that are less than or equal to a specified value.

$ne Matches all values that are not equal to a specified value.

$nin Matches none of the values specified in an array.


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

Name 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 predicate and returns documents that do not match the
query predicate.

$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 either clause.

Element: Element operators return data based on field existence or data types.

Name Description

$exists Matches documents that have the specified field.

$type Selects documents if a field is of the specified type.

Evaluation: Evaluation operators return data based on evaluations of either individual fields or
the entire collection's documents.

Name Description

$expr Allows use of aggregation expressions within the query language.

$jsonSchema Validate documents against the given JSON Schema.

$mod Performs a modulo operation on the value of a field and selects documents
with a specified result.

$regex Selects documents where values match a specified regular expression.

$where Matches documents that satisfy a JavaScript expression.


Example: Consider the sample employees Collection.

db.employees.insertMany([
{
_id:1,
firstName: "John",
lastName: "King",
email: "[email protected]",
salary: 5000,
skills: [ "Angular", "React", "MongoDB" ],
department: {
"name":"IT"
}
},
{
_id:2,
firstName: "Sachin",
lastName: "T",
email: "[email protected]",
salary: 8000,
skills: [ "Accounting", "Tax" ],
department: {
"name":"Finance"
}
},
{
_id:3,
firstName: "James",
lastName: "Bond",
email: "[email protected]",
salary: 7500,
skills: [ "Sales", "Marketing" ],
department: {
"name":"Marketing"
}
},
{
_id:4,
firstName: "Steve",
lastName: "J",
email: "[email protected]",
salary: 7000
},
{
_id:5,
firstName: "Kapil",
lastName: "D",
email: "[email protected]",
salary: 4500,
skills: [ "Accounting", "Tax" ],
department: {
"name":"Finance"
}
},
{
_id:6,
firstName: "Amitabh",
lastName: "B",
email: "[email protected]",
salary: 7000
}
])

Query 1: Return all the documents.

db.employees.find()

Query 2: Return all the documents where salary is 7000.

db.employees.find({salary: 7000})

Query 3: Find the documents where salary is greater than 7000.

db.employees.find({salary: {$gt: 7000}})

Query 4: Retrieve documents whose salary field is greater than 7000 and less than 8000.

db.employees.find({salary: {$gt: 7000, $lt: 8000}})

Projection: Use the projection parameter to specify the fields to be included in the result. The
projection parameter format is {<field>: <1 or true>, <field>: <1 or true>...} where 1 or true
includes the field, and o or false excludes the field in the result.

Query 5: Retrieve documents with the fields firstName and lastName whose salary field is 7000.

db.employees.find({salary: 7000}, {firstName:1, lastName:1})

3) Update Operations: Update operations modify existing documents in a collection. MongoDB


provides the following methods to update documents of a collection:

• db.collection.updateOne()

• db.collection.updateMany()

• db.collection.replaceOne()

In MongoDB, update operations target a single collection. All write operations in MongoDB
are atomic on the level of a single document. You can specify criteria, or filters, that identify the
documents to update. These filters use the same syntax as read operations.
db.Employee.updateOne({“Salary”:7000},{$set:{“Lastname”:”Chetana”}})

db.Employee.updateMany({“Salary”:{$lt:5000}},{$inc:{“Salary”:5000}})

Update Operators: The following table lists the update operators which can be used with
the updateOne() and updateMany() methods.

Method Description
$currentDate Sets the value of a field to current date, either as a Date or a Timestamp.
$inc Increments the value of the field by the specified amount.
$min Only updates the field if the specified value is less than the existing field value.
Only updates the field if the specified value is greater than the existing field
$max
value.
$mul Multiplies the value of the field by the specified amount.
$rename Renames a field.
$set Sets the value of a field in a document.
Sets the value of a field if an update results in an insert of a document. Has no
$setOnInsert
effect on update operations that modify existing documents.
$unset Removes the specified field from a document.

Example:

db.createCollection(student);
db.student.insertMany([
{
"student_id": 8764,
"student_name": "Paul Starc",
"address": "Hostel 1",
"age": 16,
"roll_no":199406
},
{
"student_id": 8765,
"student_name": "Andrew Boult",
"address": "Hostel 2",
"age": 18,
"roll_no":199408
}
]);

Query 1: Insert new students details into the collection


Query 2: Retrieve all the student details whose age is greater than 18
Query 3: Retrieve student_id and student_name who are staying in hostel 2.

Using the updateOne Method: An update operation in MongoDB can be done by adding a new
field, removing a field, or updating an existing field. The updateOne method updates a single
document in a collection based on the applied query filter. It first finds the document that
matches the filter and then updates the specified fields.

In addition, we can use different operators such as $set, $unset, $inc, etc., with the update method.

To demonstrate, let’s look into the query to update a single document of a collection:

db.student.updateOne(
{
"student_name" : "Paul Starc"
},
{
$set: {
"address" : "Hostel 2"
}
}
);
Output: {
"acknowledged":true,
"matchedCount":1,
"modifiedCount":1
}
Using the updateMany Method: The updateMany method updates all the documents in
MongoDB collections that match the given filter. One of the benefits of using the updateMany is
that we can update multiple documents without losing the fields of old documents.

db.student.updateMany(
{
age: {
$lt: 20
}
},
{
$set:{
"Review" : true
}
}
);
Output: {
"acknowledged":true,
"matchedCount":2,
"modifiedCount":2
}
Here, matchedCount contains the number of matched documents,
whereas modifiedCount contains the modified documents number.
Using the replaceOne Method: The replaceOne method of MongoDB replaces the entire
document. One of the drawbacks of the replaceOne is that all the older fields will be replaced by
the new fields, and the older fields will also be lost:
db.student.replaceOne(
{
"student_id": 8764
},
{
"student_id": 8764,
"student_name": "Paul Starc",
"address": "Hostel 2",
"age": 18,
"roll_no":199406
}
);
Output: {
"acknowledged":true,
"matchedCount":1,
"modifiedCount":1
}
If no matches are found, the operation returns the matchedCount as 0:
{
"acknowledged":true,
"matchedCount":0,
"modifiedCount":0
}
4) Delete Operations: Delete operations remove documents from a collection. MongoDB
provides the following methods to delete documents of a collection:

• db.collection.deleteOne()

• db.collection.deleteMany()

In MongoDB, delete operations target a single collection. All write operations in MongoDB
are atomic on the level of a single document.

You can specify criteria, or filters, that identify the documents to remove. These filters use the
same syntax as read operations.

The following deletes a document from the employees collection.

db.employees.deleteOne({ salary:7000 })

Note: The above command deletes the first matching document even if multiple documents match
with the specified criteria.

The following deletes all documents from the employees collection that match with the specified
criteria.

db.employees.deleteMany({ salary:7000 })

The following deletes all documents where salary is less than 7000.

db.employees.deleteMany({ salary: { $lt:7000} })

If you specify an empty criteria then it will delete all documents in a collection.
db.employees.deleteMany({ }) //deletes all documents

MongoDB Exercises Practice

We will consider some collections that we will use to perform various operations related to
the MongoDB, which are defined below:

1. Movies Collection

The Movies collection stores detailed information about each movie available for booking. This
includes essential attributes such as the title, genre, release year, duration, ratings, and a list of
actors. This data allows users to browse and select movies based on their preferences.

{
"movie_id": "UUID",
"title": "String",
"genre": "String",
"release_year": "Number",
"duration": "Number", // in minutes
"ratings": "Number", // Average rating between 0 and 5
"actors": ["Array of Actor Names"]
}

2. Theaters Collection

The Theaters collection contains information about the different theaters where movies are
screened. Key attributes include the theaters name, location (city, state, and country) and its
seating capacity. This information is crucial for users to choose a convenient location for their
movie experience.

{
"theater_id": "UUID",
"name": "String",
"location": {
"city": "String",
"state": "String",
"country": "String"
},
"seating_capacity": "Number"
}

3. Users Collection

The Users collection is designed to store information about the customers who use the booking
system. It includes attributes such as the users name, email, date of birth and loyalty points. This
data helps in managing user accounts and providing personalized services.

{
"user_id": "UUID",
"name": "String",
"email": "String",
"date_of_birth": "Date",
"loyalty_points": "Number"
}

4. Bookings Collection

The Bookings collection records all the bookings made by users. It includes details such as
the user ID, movie ID, theater ID, number of seats booked, total price, and the booking date.
This collection is essential for tracking user reservations and managing the overall booking
process.

{
"booking_id": "UUID",
"user_id": "UUID", // Reference to Users collection
"movie_id": "UUID", // Reference to Movies collection
"theater_id": "UUID", // Reference to Theaters collection
"seats_booked": "Number", // Number of seats booked
"total_price": "Number", // Total price for the booking
"booking_date": "Date" // Date and time of the booking
}
To better understand and work with the Movie Booking System schema, here are a series of
practice questions that cover basic CRUD operations and data retrieval.

MongoDB Exercises Questions

Q1. Insert a new movie into the Movies collection.

db.movies.insertOne({
"movie_id": "1",
"title": "Inception",
"genre": "Sci-Fi",
"release_year": 2010,
"duration": 148,
"ratings": 4.8,
"actors": ["Leonardo DiCaprio", "Joseph Gordon-Levitt", "Elliot Page"]
});

Output:

{
"acknowledged": true,
"insertedId": "1"
}

Explanation: The movie "Inception" is inserted into the collection successfully. The movie_id is
manually set to "1", and no ObjectId is generated.

Q2. Insert multiple users into the Users collection.

db.users.insertMany([
{
"user_id": "1",
"name": "John Doe",
"email": "[email protected]",
"date_of_birth": ISODate("1985-04-23"),
"loyalty_points": 120
},
{
"user_id": "2",
"name": "Jane Smith",
"email": "[email protected]",
"date_of_birth": ISODate("1990-07-12"),
"loyalty_points": 50
}
]);

Output:

{
"acknowledged": true,
"insertedIds": {
"0": "1",
"1": "2"
}
}

Explanation: Two users are successfully inserted into the collection. The user_id values "1" and
"2" are assigned to John Doe and Jane Smith, respectively.

Q3. Find all movies in the "Action" genre.

db.movies.find({ "genre": "Action" });

Output:

[]

Explanation: Since no "Action" genre movies have been inserted yet, the query returns an empty
array.

Q4. Find all theaters in the city "New York".

db.theaters.find({ "location.city": "New York" });


Output:

[]

Explanation: No theaters located in New York have been inserted into the collection yet, so the
result is an empty array..

Q5. Update the seating capacity of a theater with ID "1".

db.theaters.updateOne(
{ "theater_id": "1" },
{ $set: { "seating_capacity": 300 } }
);

Output:

{
"acknowledged": true,
"matchedCount": 0,
"modifiedCount": 0
}

Explanation: Since there is no theater with theater_id: "1" in the collection, no matching
document is found, and no update is made. matchedCount and modifiedCount remain 0.

Q6. Delete a movie by its title.

db.movies.deleteOne({ "title": "Inception" });

Output:

{
"acknowledged": true,
"deletedCount": 1
}

Explanation: The movie "Inception" is successfully deleted from the collection,


and deletedCount confirms that one document was removed.
Q7. Retrieve all bookings made by the user with ID "2".

db.bookings.find({ "user_id": "2" });

Output:

[]

Explanation: Since there are no bookings made by the user with ID "2" in the collection, the query
returns an empty array.

Q8. Find a movie by its title and display only the title and genre fields.

db.movies.find(
{ "title": "Inception" },
{ "title": 1, "genre": 1, "_id": 0 }
);

Output:

[]

Explanation: Since the movie "Inception" was deleted in query 6, there are no results to return for
this query.

Q9. Find users who have more than 100 loyalty points.

db.users.find({ "loyalty_points": { $gt: 100 } });

Output:

[
{
"user_id": "1",
"name": "John Doe",
"email": "[email protected]",
"date_of_birth": ISODate("1985-04-23"),
"loyalty_points": 120
}
]

Explanation: John Doe has 120 loyalty points, which is greater than 100, so his record is returned.

Q10. Insert a new booking into the Bookings collection.

db.bookings.insertOne({
"booking_id": "1",
"user_id": "1",
"movie_id": "1",
"theater_id": "1",
"seats_booked": 2,
"total_price": 30,
"booking_date": ISODate("2023-09-10")
});

Output:

{
"acknowledged": true,
"insertedId": "1"
}

Explanation: A new booking is inserted successfully into the collection with booking_id: "1".

Q11. Find all users born after 1990.

db.users.find({ "date_of_birth": { $gt: ISODate("1990-01-01") } });

Output:

[
{
"user_id": "2",
"name": "Jane Smith",
"email": "[email protected]",
"date_of_birth": ISODate("1990-07-12"),
"loyalty_points": 50
}
]

Explanation: Jane Smith was born after January 1, 1990, so her record is returned.

Q12. Update the ratings of the movie "Inception" to 4.9.

db.movies.updateOne(
{ "title": "Inception" },
{ $set: { "ratings": 4.9 } }
);

Output:

{
"acknowledged": true,
"matchedCount": 0,
"modifiedCount": 0
}

Explanation: Since "Inception" was deleted in query 6, no document is matched or updated.

Q13. Find all movies released in or after 2015.

db.movies.find({ "release_year": { $gte: 2015 } });

Output:

[]

Explanation: No movies released in or after 2015 have been inserted into the collection yet, so
the query returns an empty array.

Q14. Find all theaters in the state of "California".

db.theaters.find({ "location.state": "California" });

Output:
[]

Explanation: No theaters located in California have been inserted yet, so the result is an empty
array.

Q15. Delete all bookings for the movie "Inception".

db.bookings.deleteMany({ "movie_id": "1" });

Output:

{
"acknowledged": true,
"deletedCount": 1
}

Explanation: Since one booking for the movie "Inception" exists (inserted in query 10), it is
deleted.

Q16. Insert a new theater into the Theaters collection.

db.theaters.insertOne({
"theater_id": "2",
"name": "Regal Cinemas",
"location": { "city": "San Francisco", "state": "California", "country": "USA" },
"seating_capacity": 400
});

Output:

{
"acknowledged": true,
"insertedId": "2"
}

Explanation: A new theater is inserted successfully into the collection with theater_id: "2".

Q17. Find the first 5 movies sorted by release year in descending order.
db.movies.find().sort({ "release_year": -1 }).limit(5);

Output:

[]

Explanation: Since only one movie (which was deleted) was inserted, no results are returned.

Q18. Count how many movies are in the "Sci-Fi" genre.

db.movies.countDocuments({ "genre": "Sci-Fi" });

Output:

Explanation: The movie "Inception" was deleted, so there are no movies in the "Sci-Fi" genre.

Q19. Find all users who have exactly 50 loyalty points.

db.users.find({ "loyalty_points": 50 });

Output:

[
{
"user_id": "2",
"name": "Jane Smith",
"email": "[email protected]",
"date_of_birth": ISODate("1990-07-12"),
"loyalty_points": 50
}
]

Explanation: Jane Smith has exactly 50 loyalty points, so her record is returned.

Q20. Update the name of the user with ID "1" to "Johnny Doe".

db.users.updateOne(
{ "user_id": "1" },
{ $set: { "name": "Johnny Doe" } }
);

Output:

{
"acknowledged": true,
"insertedId": "1"
}

Explanation: A new review is inserted successfully into the collection with review_id: "1".

Q21. Find all movies where "Leonardo DiCaprio" is one of the actors.

db.movies.find({ "actors": "Leonardo DiCaprio" });

Output:

[
{
"movie_id": "1",
"title": "Inception",
"genre": "Sci-Fi",
"release_year": 2010,
"duration": 148,
"ratings": 4.9,
"actors": ["Leonardo DiCaprio", "Joseph Gordon-Levitt", "Elliot Page", "Tom Hardy"]
}
]

Explanation: The query finds the movie "Inception" where "Leonardo DiCaprio" is listed in
the actors array.

Q22. Add a new actor to the "Inception" movie.

db.movies.updateOne(
{ "title": "Inception" },
{ $push: { "actors": "Tom Hardy" } }
);

Output:

{
"acknowledged": true,
"matchedCount": 1,
"modifiedCount": 1
}

Explanation: This shows that one document was matched (i.e., the movie "Inception") and one
was modified (i.e., "Tom Hardy" was added to the actors array).

Q23. Retrieve all bookings made in September 2023.

db.bookings.find({
"booking_date": {
$gte: ISODate("2023-09-01"),
$lt: ISODate("2023-10-01")
}
});

Output:

[
{
"booking_id": "1",
"user_id": "1",
"movie_id": "1",
"theater_id": "1",
"seats_booked": 2,
"total_price": 30,
"booking_date": ISODate("2023-09-10")
},
{
"booking_id": "2",
"user_id": "2",
"movie_id": "3",
"theater_id": "2",
"seats_booked": 4,
"total_price": 60,
"booking_date": ISODate("2023-09-11")
},
{
"booking_id": "3",
"user_id": "3",
"movie_id": "1",
"theater_id": "1",
"seats_booked": 1,
"total_price": 15,
"booking_date": ISODate("2023-09-12")
}
]

Explanation: This query retrieves all bookings made in September 2023, showing three bookings
during that time period.

Q24. Calculate the total price for all bookings made by the user with ID "1".

db.bookings.aggregate([
{ $match: { "user_id": "1" } },
{ $group: { _id: null, total: { $sum: "$total_price" } } }
]);

Output:

[
{
"_id": null,
"total": 30
}
]

Explanation: The aggregation query calculates the sum of the total_price for all bookings made
by the user with user_id "1", which amounts to 30.

Q25. Delete all users who have less than 10 loyalty points.

db.users.deleteMany({ "loyalty_points": { $lt: 10 } });

Output:

{
"acknowledged": true,
"deletedCount": 0
}

Explanation: No users had less than 10 loyalty points in the dataset, so no documents were deleted.

Q26. Find all movies that are either in the "Action" or "Adventure" genres.

db.movies.find({ "genre": { $in: ["Action", "Adventure"] } });

Output:

[]

Explanation: No movies in the collection match the genres "Action" or "Adventure" based on the
available dataset.

Q27. Insert multiple bookings into the Bookings collection.

db.bookings.insertMany([
{
"booking_id": "2",
"user_id": "2",
"movie_id": "3",
"theater_id": "2",
"seats_booked": 4,
"total_price": 60,
"booking_date": ISODate("2023-09-11")
},
{
"booking_id": "3",
"user_id": "3",
"movie_id": "1",
"theater_id": "1",
"seats_booked": 1,
"total_price": 15,
"booking_date": ISODate("2023-09-12")
}
]);

Output:

{
"acknowledged": true,
"insertedIds": {
"0": "2",
"1": "3"
}
}

Explanation: Two new booking documents were successfully inserted into


the bookings collection.

Q28. Find the total number of bookings made for the movie with ID "1".

db.bookings.countDocuments({ "movie_id": "1" });

Output: 3
Explanation: There are 3 bookings associated with the movie that has movie_id "1".

Q29. Find all theaters in the USA with a seating capacity greater than 300.

db.theaters.find({
"location.country": "USA",
"seating_capacity": { $gt: 300 }
});

Output:

[
{
"theater_id": "2",
"name": "Regal Cinemas",
"location": {
"city": "San Francisco",
"state": "California",
"country": "USA"
},
"seating_capacity": 400
}
]

Explanation: This query finds all theaters in the USA where the seating_capacity exceeds 300.
The "Regal Cinemas" theater in San Francisco is retrieved.

Q30. Update the loyalty points of all users who have booked more than 3 seats to give them
an extra 10 points.

db.bookings.aggregate([
{ $group: { _id: "$user_id", total_seats: { $sum: "$seats_booked" } } },
{ $match: { total_seats: { $gt: 3 } } }
]).forEach(function(user) {
db.users.updateOne(
{ "user_id": user._id },
{ $inc: { "loyalty_points": 10 } }
);
});

Output:

[
{
"acknowledged": true,
"matchedCount": 1,
"modifiedCount": 1
},
{
"acknowledged": true,
"matchedCount": 1,
"modifiedCount": 1
}
]

Explanation: The users with user_id "2" and "3" each booked more than 3 seats, so their loyalty
points were incremented by 10.

Q31. Find all movies where the genre is not "Comedy".

db.movies.find({ "genre": { $ne: "Comedy" } });

Output:

[
{
"movie_id": "1",
"title": "Inception",
"genre": "Sci-Fi",
"release_year": 2010,
"duration": 148,
"ratings": 4.9,
"actors": ["Leonardo DiCaprio", "Joseph Gordon-Levitt", "Elliot Page", "Tom Hardy"]
}
]

Explanation: This query retrieves all movies whose genre is not "Comedy". The movie
"Inception" is returned.

Q32. Find the number of seats booked for each movie.

db.bookings.aggregate([
{ $group: { _id: "$movie_id", total_seats: { $sum: "$seats_booked" } } }
]);

Output:

[
{ "_id": "1", "total_seats": 3 },
{ "_id": "3", "total_seats": 4 }
]

Explanation: This query groups bookings by movie_id and sums up the seats_booked for each
movie.

Q33. Find all users who booked seats in "California" theaters.

db.bookings.aggregate([
{ $lookup: { from: "theaters", localField: "theater_id", foreignField: "theater_id", as:
"theater_info" } },
{ $unwind: "$theater_info" },
{ $match: { "theater_info.location.state": "California" } },
{ $group: { _id: "$user_id" } }
]);

Output:
[
{ "_id": "1" },
{ "_id": "2" }
]

Explanation: This query retrieves the users who booked seats in theaters located in California by
performing a lookup from the theaters collection.

Q34. Increase the ticket price for all bookings made after 2023-09-10 by 5%.

db.theaters.updateMany(
{ "location.state": "California" },
{ $set: { "seating_capacity": 500 } }
);

Output:

{
"acknowledged": true,
"matchedCount": 2,
"modifiedCount": 2
}

Explanation: This query updates the ticket price of bookings made after September 10, 2023, by
increasing the total_price by 5%.

Q35. Find the average rating of all movies in the "Sci-Fi" genre.

db.movies.aggregate([
{ $match: { "genre": "Sci-Fi" } },
{ $group: { _id: null, avg_rating: { $avg: "$ratings" } } }
]);

Output:
[
{ "_id": null, "avg_rating": 4.9 }
]

Explanation: This query calculates the average rating of all movies in the "Sci-Fi" genre.

Q36. Find the movie with the longest duration.

db.movies.aggregate([
{ $match: { "genre": "Sci-Fi" } },
{ $group: { _id: null, avg_duration: { $avg: "$duration" } } }
]);

Output:

[
{
"movie_id": "1",
"title": "Inception",
"genre": "Sci-Fi",
"release_year": 2010,
"duration": 148,
"ratings": 4.9,
"actors": ["Leonardo DiCaprio", "Joseph Gordon-Levitt", "Elliot Page", "Tom Hardy"]
}
]

Explanation: This query sorts the movies by duration in descending order and returns the one with
the longest duration, which is "Inception" with 148 minutes.

Q37. Find all bookings where the user booked more than 2 seats.

db.bookings.find({ "seats_booked": { $gt: 2 } });

Output:
[
{
"booking_id": "2",
"user_id": "2",
"movie_id": "3",
"theater_id": "2",
"seats_booked": 4,
"total_price": 60,
"booking_date": ISODate("2023-09-11")
}
]

Explanation: This query retrieves bookings where more than 2 seats were booked. The booking
with seats_booked equal to 4 is returned.

Q38. Find all movies that have both "Tom Hardy" and "Leonardo DiCaprio" in their cast.

db.movies.find({ "actors": { $all: ["Tom Hardy", "Leonardo DiCaprio"] }});

Output:

[
{
"movie_id": "1",
"title": "Inception",
"genre": "Sci-Fi",
"release_year": 2010,
"duration": 148,
"ratings": 4.9,
"actors": ["Leonardo DiCaprio", "Joseph Gordon-Levitt", "Elliot Page", "Tom Hardy"]
}
]

Explanation: This query finds the movie "Inception" where both "Tom Hardy" and "Leonardo
DiCaprio" are part of the cast.
Q39. Find all users who have not made any bookings.

db.users.find({ "user_id": { $nin: db.bookings.distinct("user_id") }});

Output:

[
{
"user_id": "4",
"name": "Eve",
"loyalty_points": 15
}
]

Explanation: This query retrieves users who have not made any bookings by excluding user IDs
present in the bookings collection.

Q40. Delete all movies that have less than 3 stars in ratings.

db.movies.deleteMany({ "ratings": { $lt: 3 } });

Output:

{
"acknowledged": true,
"deletedCount": 0
}

Explanation: No movies in the collection have less than 3 stars, so no documents were deleted.

Excercises:

1) {

"_id": "emp001",

"name": {

"first": "John",
"last": "Doe"

},

"email": "[email protected]",

"phone": "123-456-7890",

"department": "Engineering",

"designation": "Software Engineer",

"salary": 75000,

"date_of_joining": "2022-03-15",

"address": {

"street": "123 Elm Street",

"city": "San Francisco",

"state": "CA",

"zip": "94107"

},

"skills": ["JavaScript", "Node.js", "MongoDB"],

"is_active": true

Explanation:

• _id: A unique identifier for the employee (can be a string, ObjectId, etc.).

• name: A nested object containing first and last names.

• email: The employee's email address.

• phone: The employee's phone number.

• department: The department the employee belongs to.


• designation: The job title of the employee.

• salary: The salary of the employee.

• date_of_joining: The date the employee joined the company (ISO date format).

• address: A nested object for the employee's address.

• skills: An array listing the employee's skills.

• is_active: A boolean indicating if the employee is currently active.

1. Insert a Document

db.employees.insertOne({

"_id": "emp001",

"name": {

"first": "John",

"last": "Doe"

},

"email": "[email protected]",

"phone": "123-456-7890",

"department": "Engineering",

"designation": "Software Engineer",

"salary": 75000,

"date_of_joining": "2022-03-15",

"address": {

"street": "123 Elm Street",

"city": "San Francisco",


"state": "CA",

"zip": "94107"

},

"skills": ["JavaScript", "Node.js", "MongoDB"],

"is_active": true

});

2. Find All Documents

db.employees.find();

3. Find a Document by _id

db.employees.find({ "_id": "emp001" });

4. Find Documents with a Specific Field

• By Department:

db.employees.find({ "department": "Engineering" });

• By Skill:

db.employees.find({ "skills": "MongoDB" });

5. Find Documents Using Logical Operators

• Employees in Engineering or HR Departments:

db.employees.find({ "department": { $in: ["Engineering", "HR"] } });

• Employees with Salary Greater Than 50,000:


db.employees.find({ "salary": { $gt: 50000 } });

• Employees Active and in Engineering Department:

db.employees.find({ $and: [{ "is_active": true }, { "department": "Engineering" }] });

6. Update a Document

• Update Salary:

db.employees.updateOne(

{ "_id": "emp001" },

{ $set: { "salary": 80000 } }

);

• Add a New Skill:

db.employees.updateOne(

{ "_id": "emp001" },

{ $addToSet: { "skills": "React" } }

);

7. Delete a Document

• Delete by _id:

db.employees.deleteOne({ "_id": "emp001" });

8. Count Documents

• Count Active Employees:

db.employees.countDocuments({ "is_active": true });


9. Aggregate Queries

• Group by Department and Calculate Average Salary:

db.employees.aggregate([

{ $group: { _id: "$department", averageSalary: { $avg: "$salary" } } }

]);

• Find Top Earners (Salary > 70,000):

db.employees.aggregate([

{ $match: { "salary": { $gt: 70000 } } },

{ $sort: { "salary": -1 } }

]);

10. Project Specific Fields

• Show Name and Email Only:

db.employees.find({}, { "name": 1, "email": 1, "_id": 0 });

11. Text Search

• Find Employees Matching Skills:

db.employees.find({ "skills": { $regex: "Node", $options: "i" } });

You might also like