Lecture 9 - MongoDB
Multiple Choice Questions
1. What type of database is MongoDB? a) Relational database b) NoSQL document
database c) Graph database d) SQL database
Answer: b) NoSQL document database - MongoDB is a document-oriented NoSQL
database that stores data in flexible, JSON-like documents.
1. In MongoDB, what is the equivalent of a table in relational databases? a) Document
b) Collection c) Field d) Index
Answer: b) Collection - In MongoDB, collections are equivalent to tables in relational
databases. They store groups of related documents.
1. Which of the following is the correct way to create a new document in MongoDB? a)
db.collection.add() b) db.collection.create() c) db.collection.insertOne() d)
db.collection.newDoc()
Answer: c) db.collection.insertOne() - The insertOne() method is used to insert a single
document into a collection.
1. What is the MongoDB query operator used to match values that are greater than a
specified value? a) $gt b) $more c) $greater d) $higher
Answer: a) $gt - The $gt operator is used to match values that are greater than a
specified value.
1. Which of the following is NOT a valid data type in MongoDB? a) ObjectId b) Date c)
Boolean d) Varchar
Answer: d) Varchar - Varchar is a SQL data type, not a MongoDB data type. MongoDB
uses String instead.
State Questions
1. State the difference between SQL and NoSQL databases.
Answer: SQL (relational) databases and NoSQL databases differ in several key ways:
• Structure: SQL databases use a structured schema with tables, rows, and columns,
while NoSQL databases (like MongoDB) are schema-less and store data in various
formats such as documents, key-value pairs, wide-column stores, or graphs.
• Schema: SQL databases require a predefined schema before data insertion, while
NoSQL databases have flexible schemas allowing for dynamic changes without
disrupting applications.
• Scaling: SQL databases typically scale vertically (by adding more power to existing
hardware), while NoSQL databases are designed to scale horizontally (by adding
more servers).
• Query Language: SQL databases use Structured Query Language (SQL) for
defining and manipulating data, while NoSQL databases use various query
languages specific to their data model.
• ACID Compliance: SQL databases are generally ACID (Atomicity, Consistency,
Isolation, Durability) compliant, while many NoSQL databases sacrifice some ACID
properties for performance and scalability.
• Data Relationships: SQL databases handle relationships through foreign keys and
joins, while NoSQL databases often store related data together in a single
document or use references.
• State what sharding is in MongoDB and why it's useful.
Answer: Sharding in MongoDB is a method for distributing data across multiple
machines (shards). It's a horizontal scaling strategy that allows MongoDB to support
deployments with very large data sets and high throughput operations.
Sharding is useful because:
• It allows databases to grow beyond the storage capacity of a single server
• It improves read/write performance by distributing operations across multiple
servers
• It enables higher throughput by increasing the number of concurrent operations
that can be handled
• It provides high availability, as data is distributed across multiple servers
• It allows for geographic distribution of data, reducing latency for globally
distributed applications
• It helps maintain performance as data volume and request rates increase
In MongoDB, sharding is implemented at the collection level, with data distributed
according to a shard key that determines how the data is partitioned.
1. State the purpose of indexes in MongoDB and how they improve performance.
Answer: Indexes in MongoDB serve to improve the efficiency of query operations. They
work by creating a data structure that stores a small portion of the collection's data in an
easy-to-traverse form.
Indexes improve performance by:
• Reducing the number of documents MongoDB needs to scan to find the query
results
• Limiting the number of disk I/O operations required to fulfill a query
• Enabling more efficient use of system resources (CPU, memory)
• Supporting efficient sorting operations by pre-sorting the indexed fields
• Enforcing uniqueness constraints on fields (with unique indexes)
• Facilitating geospatial queries (with geospatial indexes)
• Supporting text search capabilities (with text indexes)
Without indexes, MongoDB would need to perform a collection scan, examining every
document in a collection to find matches to a query, which becomes increasingly
inefficient as collections grow larger.
1. State what the MongoDB aggregation pipeline is and provide a simple example.
Answer: The MongoDB aggregation pipeline is a framework for data processing that
allows you to transform documents as they pass through a series of stages. Each stage
performs an operation on the input documents and passes the results to the next stage.
The pipeline provides a way to analyze data and compute aggregated results.
Key features of the aggregation pipeline: - Processes data records and returns computed
results - Can perform operations like filtering, grouping, sorting, and transforming data -
Supports complex analytics and data processing tasks - Can operate on large data sets
efficiently
Simple example: ```javascript db.sales.aggregate([ // Stage 1: Filter documents by date
{ $match: { date: { $gte: new Date("2023-01-01"), $lt: new Date("2024-01-01") } } },
// Stage 2: Group documents by product and calculate total sales
{ $group: {
_id: "$product",
totalSales: { $sum: "$amount" },
count: { $sum: 1 }
} },
// Stage 3: Sort by total sales in descending order
{ $sort: { totalSales: -1 } }
]) ``` This example filters sales from 2023, groups them by product, calculates total
sales and count for each product, and sorts the results by total sales in descending order.
1. State the difference between insertOne() and insertMany() methods in MongoDB.
Answer: The insertOne() and insertMany() methods in MongoDB are used to add
documents to a collection, but they differ in several ways:
insertOne(): - Inserts a single document into a collection - Takes a single document as
its parameter - Returns a result object with information about the operation, including
the _id of the inserted document - Example:
db.collection.insertOne({ name: "John", age: 30 })
insertMany(): - Inserts multiple documents into a collection in a single operation - Takes
an array of documents as its parameter - More efficient than multiple insertOne()
operations for bulk inserts - Returns a result object with information about the
operation, including an array of the _ids of all inserted documents - Supports ordered or
unordered inserts (with the ordered option) - Example:
db.collection.insertMany([{ name: "John", age: 30 }, { name: "Jane", age: 25 }])
Both methods can throw write errors if the operation fails, and both support write
concerns to ensure durability of writes.
Code Output Questions
1. What is the output of the following MongoDB query?
db.users.find({ age: { $gt: 25 } }).count()
// Assuming the collection has 5 documents with age > 25
Answer: 5 - The query finds all documents in the users collection where the age field is
greater than 25, and the count() method returns the number of documents that match
the query criteria, which is 5.
1. What is the output of the following MongoDB query?
db.products.updateOne(
{ name: "Phone" },
{ $set: { price: 500 } }
)
// Assuming there is one document with name "Phone"
Answer: { "acknowledged": true, "matchedCount": 1, "modifiedCount": 1 } The
updateOne() method returns an object that includes: - acknowledged: true (indicating
the operation was acknowledged by the server) - matchedCount: 1 (one document
matched the filter criteria) - modifiedCount: 1 (one document was modified)
Note: If the price was already 500, modifiedCount would be 0.
1. What is the output of the following MongoDB query?
db.orders.find().sort({ date: -1 }).limit(1)
// Assuming there are orders with different dates
Answer: The query will return a cursor to the most recent order document (based on the
date field). The sort({ date: -1 }) sorts in descending order (newest first), and limit(1)
restricts the result to just one document. The actual output would be the single
document with the latest date, for example: { "_id": ObjectId("..."), "date":
ISODate("2023-05-15T14:30:00Z"), "customer": "John Doe", "items": [...], "total": 125.99 }
1. What is the output of the following MongoDB query?
db.inventory.find({ qty: { $in: [20, 50] } })
// Assuming there are 3 documents with qty either 20 or 50
Answer: The query will return a cursor to all documents where the qty field is either 20
or 50. Since there are 3 such documents, the output would be those 3 documents, for
example: [ { "_id": ObjectId("..."), "item": "notebook", "qty": 20, "price": 10.99 }, { "_id":
ObjectId("..."), "item": "pencil", "qty": 50, "price": 1.99 }, { "_id": ObjectId("..."), "item":
"eraser", "qty": 20, "price": 0.99 } ]
1. What is the output of the following MongoDB query?
db.restaurants.distinct("cuisine")
// Assuming there are restaurants with cuisines: Italian, Chinese, Indian, Italian,
Mexican
Answer: [ "Italian", "Chinese", "Indian", "Mexican" ] - The distinct() method returns an
array of unique values for the specified field. Even though "Italian" appears twice in the
collection, it only appears once in the result.
Find Errors Questions
1. Find and fix the error in the following MongoDB query:
db.users.find({ age > 30 })
Answer: The query syntax is incorrect. In MongoDB, query conditions must be specified
as field-value pairs. Corrected code: javascript db.users.find({ age: { $gt: 30 } })
1. Find and fix the error in the following MongoDB query:
db.products.update(
{ category: "Electronics" }
{ price: 100 }
)
Answer: There's a missing comma between the filter and update documents. Also, the
update document needs an update operator like $set. Corrected code: javascript
db.products.update( { category: "Electronics" }, { $set: { price: 100 } } )
1. Find and fix the error in the following MongoDB query:
db.orders.insertOne({
customer: "John",
items: ["Book", "Pen"]
total: 25.99
})
Answer: There's a missing comma after the items array. Corrected code: javascript
db.orders.insertOne({ customer: "John", items: ["Book", "Pen"], total: 25.99 })
1. Find and fix the error in the following MongoDB query:
db.inventory.deleteOne(
_id: ObjectId("507f1f77bcf86cd799439011")
)
Answer: The filter document needs to be enclosed in curly braces. Corrected code:
javascript db.inventory.deleteOne({ _id: ObjectId("507f1f77bcf86cd799439011") })
1. Find and fix the error in the following MongoDB query:
db.employees.aggregate([
{ $group: { _id: "$department", avgSalary: { $avg: "salary" } } }
])
Answer: The $avg operator requires a field path (with a $ prefix) as its argument, not a
string. Corrected code: javascript db.employees.aggregate([ { $group: { _id:
"$department", avgSalary: { $avg: "$salary" } } } ])
Write/Complete Code Questions
1. Write a MongoDB query to find all documents in a collection named "students"
where the age is greater than 18 and the grade is "A".
Answer: javascript db.students.find({ age: { $gt: 18 }, grade: "A" })
1. Complete the following MongoDB query to update multiple documents:
// Update all products in the "Electronics" category to have a 10% discount
db.products.updateMany(
// Your filter here
// Your update operation here
)
Answer: javascript // Update all products in the "Electronics" category to have a 10%
discount db.products.updateMany( { category: "Electronics" }, { $mul: { price: 0.9 } } )
Alternative solution using $set and $multiply: javascript db.products.updateMany(
{ category: "Electronics" }, [ { $set: { price: { $multiply: ["$price", 0.9] } } } ] )
1. Write a MongoDB query to create an index on the "email" field of a "users"
collection to ensure email uniqueness.
Answer: javascript db.users.createIndex( { email: 1 }, { unique: true } ) This creates an
ascending index on the email field and adds a unique constraint to ensure that no two
documents can have the same email value.
1. Complete the following MongoDB aggregation pipeline to group documents by
category and calculate the average price:
db.products.aggregate([
// Your stages here
])
Answer: ```javascript db.products.aggregate([ // Stage 1: Group by category and
calculate average price { $group: { _id: "$category", averagePrice: { $avg: "$price" },
count: { $sum: 1 } }},
// Stage 2: Sort by average price in descending order
{ $sort: { averagePrice: -1 } },
// Stage 3: Project to rename fields and format output
{ $project: {
category: "$_id",
averagePrice: { $round: ["$averagePrice", 2] },
numberOfProducts: "$count",
_id: 0
}}
]) ```
1. Write a MongoDB query to join (lookup) data from an "orders" collection with a
"customers" collection based on the customer_id field.
Answer: ```javascript db.orders.aggregate([ { $lookup: { from: "customers", localField:
"customer_id", foreignField: "_id", as: "customer_info" } }, // Optional: Unwind the
customer_info array to flatten the result { $unwind: "$customer_info" },
// Optional: Project to reshape the output
{ $project: {
order_id: "$_id",
order_date: 1,
items: 1,
total: 1,
customer_name: "$customer_info.name",
customer_email: "$customer_info.email",
customer_address: "$customer_info.address",
_id: 0
}}
]) ``` This query uses the $lookup stage to perform a left outer join between the orders
collection and the customers collection, matching documents based on the customer_id
field in orders and the _id field in customers.