0% found this document useful (0 votes)
6 views25 pages

Viva

The document provides a comprehensive overview of MongoDB query operations, including the use of WHERE clauses, logical operators like AND and OR, and various commands for inserting, updating, and deleting documents. It also covers projection operators to control the output of queries and includes practical examples and conceptual questions for better understanding. Additionally, it discusses comparison, logical, geospatial, and bitwise selectors used in MongoDB queries.

Uploaded by

deepthia2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views25 pages

Viva

The document provides a comprehensive overview of MongoDB query operations, including the use of WHERE clauses, logical operators like AND and OR, and various commands for inserting, updating, and deleting documents. It also covers projection operators to control the output of queries and includes practical examples and conceptual questions for better understanding. Additionally, it discusses comparison, logical, geospatial, and bitwise selectors used in MongoDB queries.

Uploaded by

deepthia2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 25

🔸 Conceptual Viva Questions:

1 What is the purpose of the WHERE clause in MongoDB, and how is it different from
1️⃣
SQL’s WHERE clause?
Answer: In MongoDB, the concept of a "WHERE clause" is implemented using query
documents in the find() method. Unlike SQL, which uses a structured query language,
MongoDB uses JSON-like documents to filter data.

2️⃣ How do you perform an AND operation in a MongoDB query?


Answer: The AND operation is implicit in MongoDB when you include multiple key-
value pairs in a query. You can also explicitly use $and like:

js
Copy
Edit
db.collection.find({ $and: [ { age: { $gt: 18 } }, { city: "Delhi" } ] })
3️⃣ How is the OR operation implemented in MongoDB?
Answer: You use the $or operator to combine multiple conditions where any one can
be true:

js
Copy
Edit
db.collection.find({ $or: [ { age: 25 }, { city: "Mumbai" } ] })
4️⃣ Can you nest AND and OR operations together in a single MongoDB query? How?
Answer: Yes, by combining $and and $or operators within the same query document:

js
Copy
Edit
db.collection.find({
$and: [
{ status: "active" },
{ $or: [ { age: 30 }, { city: "Delhi" } ] }
]
})
🔸 Lab Questions and Explanation:
1️⃣ Write a query to find all users whose age is greater than 25 and city is "Delhi".
Explanation: Use an implicit AND by listing both conditions:

js
Copy
Edit
db.users.find({ age: { $gt: 25 }, city: "Delhi" })
2️⃣ Find users who are either from "Delhi" or have age greater than 30.
Explanation: Use $or to combine conditions:

js
Copy
Edit
db.users.find({
$or: [ { city: "Delhi" }, { age: { $gt: 30 } } ]
})
3️⃣ Find active users whose age is between 20 and 30 and are either from "Mumbai" or
"Pune".
Explanation: Combine $and, $or, and range conditions:

js
Copy
Edit
db.users.find({
$and: [
{ status: "active" },
{ age: { $gte: 20, $lte: 30 } },
{ $or: [ { city: "Mumbai" }, { city: "Pune" } ] }
]
})
📖 Topic B: Execute MongoDB Commands — Insert, Query, Update, Delete, Projection
🔸 Conceptual Viva Questions:
1️⃣ What command is used to insert a document into a MongoDB collection?
Answer: insertOne() for a single document and insertMany() for multiple documents.
Example:

js
Copy
Edit
db.users.insertOne({ name: "Amit", age: 28, city: "Delhi" })
2️⃣ How do you retrieve documents from a MongoDB collection?
Answer: Using find() for multiple documents or findOne() for a single document.
Example:

js
Copy
Edit
db.users.find({ city: "Delhi" })
3️⃣ What is update operation in MongoDB and how is it performed?
Answer: It modifies existing documents using updateOne(), updateMany(), or
replaceOne().
Example:

js
Copy
Edit
db.users.updateOne({ name: "Amit" }, { $set: { age: 29 } })
4️⃣ How do you delete documents in MongoDB?
Answer: Using deleteOne() for one document or deleteMany() for multiple.
Example:

js
Copy
Edit
db.users.deleteOne({ name: "Amit" })
5️⃣ What is a projection in MongoDB?
Answer: It specifies which fields to return in the query result.
Example:

js
Copy
Edit
db.users.find({}, { name: 1, city: 1, _id: 0 })
🔸 Lab Questions and Explanation:
1️⃣ Insert 3 documents into a collection named "students".
Explanation:

js
Copy
Edit
db.students.insertMany([
{ name: "Rahul", age: 21, course: "BCA" },
{ name: "Sneha", age: 22, course: "MCA" },
{ name: "Priya", age: 23, course: "MBA" }
])
2️⃣ Query to display all students enrolled in "MCA".
Explanation:

js
Copy
Edit
db.students.find({ course: "MCA" })
3️⃣ Update the course of "Rahul" to "B.Tech".
Explanation:

js
Copy
Edit
db.students.updateOne(
{ name: "Rahul" },
{ $set: { course: "B.Tech" } }
)
4️⃣ Delete the student whose name is "Sneha".
Explanation:

js
Copy
Edit
db.students.deleteOne({ name: "Sneha" })
5️⃣ Query to display only the names and courses of students (excluding _id).
Explanation:

js
Copy
Edit
db.students.find({}, { name: 1, course: 1, _id: 0 })
a. Select Certain Fields and Ignore Some Fields in MongoDB
In MongoDB, when you run a find() query, you can use projection to select or ignore
specific fields in the result set.

📌 Syntax:

js
Copy
Edit
db.collection.find(filter, projection)
filter — the condition to match documents

projection — specifies which fields to include (1) or exclude (0)

📌 Example:

js
Copy
Edit
db.students.find({}, { name: 1, course: 1, _id: 0 })
👉 This will display only name and course, and exclude the _id field.

🔸 b. Display the First 5 Documents from the Results


In MongoDB, the limit() method is used to restrict the number of documents returned
in a query result.
📌 Syntax:

js
Copy
Edit
db.collection.find().limit(5)
📌 Example:

js
Copy
Edit
db.students.find().limit(5)
👉 This returns the first 5 documents from the students collection.

📌 Viva Questions for Lab Practical (Conceptual + Practical)


🔸 Conceptual Viva Questions:
1️⃣ What is the purpose of projection in a MongoDB query?
Answer: Projection allows you to control which fields to include or exclude in the
query result.

2️⃣ How do you include or exclude fields in MongoDB query results?


Answer: By using 1 to include and 0 to exclude fields in the projection part of the
find() query.

3️⃣ What is the role of _id in MongoDB queries, and how can you exclude it?
Answer: _id is automatically included in MongoDB query results. To exclude it,
explicitly set _id: 0 in the projection.

4️⃣ Can you include and exclude fields simultaneously (other than _id) in a MongoDB
projection?
Answer: No. In a single projection, you cannot mix including and excluding fields
except for _id.

5️⃣ What method is used to limit the number of documents displayed in a MongoDB query
result?
Answer: The limit() method.

6️⃣ How would you display only the first 5 documents from a MongoDB collection?
Answer: By using the limit() method along with find():

js
Copy
Edit
db.collection.find().limit(5)
7️⃣ Can you combine limit() with a projection in a single MongoDB query?
Answer: Yes. Example:

js
Copy
Edit
db.students.find({}, { name: 1, _id: 0 }).limit(5)
8️⃣ Why is it good practice to use projections when working with large MongoDB
collections?
Answer: To improve query performance by retrieving only necessary fields, reducing
network and memory overhead.

9️⃣ How do you retrieve all documents but only show name and course fields from a
students collection?
Answer:

js
Copy
Edit
db.students.find({}, { name: 1, course: 1, _id: 0 })
0️⃣
1 Is it possible to exclude multiple fields in a projection? How?
Answer: Yes, by setting each field you want to exclude to 0.
Example:

js
Copy
Edit
db.students.find({}, { age: 0, city: 0, _id: 0 })
Explanation of Topics:
🔸 a. Execute Query Selectors (Comparison Selectors, Logical Selectors)
👉 Comparison Selectors
Used to compare values in documents. Common operators:

$eq — equal

$ne — not equal

$gt — greater than

$gte — greater than or equal

$lt — less than

$lte — less than or equal

$in — matches any of the values in an array

$nin — not in an array

📌 Example:

js
Copy
Edit
db.students.find({ age: { $gt: 20 } })
👉 Logical Selectors
Combine multiple conditions.

$and — all conditions must be true

$or — any one condition must be true

$nor — none of the conditions should be true

$not — negates a condition

📌 Example:

js
Copy
Edit
db.students.find({
$and: [ { course: "BCA" }, { age: { $gte: 21 } } ]
})
🔸 b. Execute Query Selectors (Geospatial Selectors, Bitwise Selectors)
👉 Geospatial Selectors
Used for location-based queries on fields with geospatial data (2dsphere or 2d
index)

$near — documents nearest to a point

$geoWithin — documents within a geometry

$geoIntersects — documents that intersect with a geometry

📌 Example:

js
Copy
Edit
db.places.find({
location: {
$near: {
$geometry: { type: "Point", coordinates: [ 77.5946, 12.9716 ] },
$maxDistance: 5000
}
}
})
👉 Bitwise Selectors
Used for queries on numeric fields using bitwise operations.

$bitsAllSet

$bitsAnySet

$bitsAllClear

$bitsAnyClear

📌 Example:

js
Copy
Edit
db.flags.find({ permissions: { $bitsAllSet: [1, 3] } })
📌 Viva Questions for Lab Practical (Conceptual + Practical)
🔸 Conceptual Viva Questions
📌 Comparison and Logical Selectors:
1️⃣ What is the purpose of comparison selectors in MongoDB?
Answer: To compare field values against specified conditions like greater than,
equal to, less than, etc.

2️⃣ Name four comparison operators in MongoDB.


Answer: $eq, $gt, $lt, $in

3️⃣ How do logical selectors like $and and $or work in MongoDB?
Answer: $and returns documents satisfying all conditions, while $or returns
documents satisfying at least one condition.

4️⃣ Can you nest logical selectors inside each other? Give an example.
Answer: Yes.
js
Copy
Edit
db.students.find({
$and: [
{ age: { $gt: 20 } },
{ $or: [ { course: "BCA" }, { course: "MCA" } ] }
]
})
5️⃣ What is the difference between $in and $nin operators?
Answer: $in matches any value in an array; $nin matches values not present in the
array.

📌 Geospatial and Bitwise Selectors:


6️⃣ What type of data is required to perform a geospatial query in MongoDB?
Answer: Location data stored as GeoJSON objects and indexed with a 2dsphere or 2d
index.

7️⃣ Name three geospatial query operators in MongoDB.


Answer: $near, $geoWithin, $geoIntersects

8️⃣ What is the purpose of the $near operator?


Answer: To find documents sorted by proximity to a specified point.

9️⃣ What are bitwise query selectors used for in MongoDB?


Answer: To query documents based on specific bits set or cleared in a numeric
field.

0️⃣ Name two bitwise operators and explain them.


1
Answer:

$bitsAllSet — Matches documents where all specified bit positions are 1

$bitsAnyClear — Matches documents where any of the specified bit positions are 0

🔸 Practical Viva Questions


1️⃣ Write a query to find all students whose age is greater than 22.

js
Copy
Edit
db.students.find({ age: { $gt: 22 } })
2️⃣ Write a query to find students enrolled in either "BCA" or "MCA".

js
Copy
Edit
db.students.find({
$or: [ { course: "BCA" }, { course: "MCA" } ]
})
3️⃣ Write a query using $and to find students with age greater than 20 and course
"BCA".

js
Copy
Edit
db.students.find({
$and: [ { age: { $gt: 20 } }, { course: "BCA" } ]
})
4️⃣ Write a geospatial query to find places within 5 km of a specific point.

js
Copy
Edit
db.places.find({
location: {
$near: {
$geometry: { type: "Point", coordinates: [ 77.5946, 12.9716 ] },
$maxDistance: 5000
}
}
})
5️⃣ Write a bitwise query to find documents where bits 1 and 3 are set in the
permissions field.

js
Copy
Edit
db.flags.find({ permissions: { $bitsAllSet: [1, 3] } })
Explanation: Projection Operators in MongoDB
MongoDB projection operators allow you to control the shape and content of the
documents returned by a query — either by including/excluding fields or limiting
elements of an array field.

1️⃣ The $ Projection Operator


👉 Returns the first matching element from an array based on the query condition.

Example Collection:

js
Copy
Edit
db.students.insertOne({
name: "Ankit",
scores: [ 85, 90, 78, 88 ]
})
Query:

js
Copy
Edit
db.students.find(
{ scores: 90 },
{ "scores.$": 1, _id: 0 }
)
✅ Result:
Only the matching score 90 is returned in the scores array.

2️⃣ The $elemMatch Projection Operator


👉 Returns the first array element that matches the specified criteria in the
projection.

Example Collection:

js
Copy
Edit
db.students.insertOne({
name: "Sneha",
scores: [ { subject: "Math", marks: 85 }, { subject: "Science", marks: 90 } ]
})
Query:

js
Copy
Edit
db.students.find(
{},
{ name: 1, scores: { $elemMatch: { subject: "Math" } }, _id: 0 }
)
✅ Result:
Only the matching subdocument { subject: "Math", marks: 85 } is returned.

3️⃣ The $slice Projection Operator


👉 Limits the number of elements returned from an array.

Example Collection:

js
Copy
Edit
db.blog.insertOne({
title: "MongoDB Tutorial",
comments: [ "Good", "Helpful", "Detailed", "Awesome", "Must-read" ]
})
Query:

js
Copy
Edit
db.blog.find(
{},
{ title: 1, comments: { $slice: 2 }, _id: 0 }
)
✅ Result:
Returns only the first two comments.

📌 Viva Questions on Projection Operators (Conceptual + Practical)


🔸 Conceptual Viva Questions
1️⃣ What is the purpose of projection operators in MongoDB queries?
Answer: To control which fields and array elements are included in the query
result.

2️⃣ What does the $ projection operator do in MongoDB?


Answer: It returns the first matching element from an array based on the query
condition.

3️⃣ When would you use the $elemMatch projection operator?


Answer: To return the first array element matching specified criteria within an
array of embedded documents.

4️⃣ What is the difference between $elemMatch in the query selector vs in the
projection?
Answer: In the query selector, it filters documents; in the projection, it controls
which array elements are returned.

5️⃣ How does the $slice operator work in MongoDB projections?


Answer: It limits the number of elements returned from an array in the query
result.

6️⃣ Can you use $slice to retrieve the last few elements of an array? How?
Answer: Yes, by passing a negative number to $slice.
Example:

js
Copy
Edit
{ comments: { $slice: -2 } }
returns the last 2 comments.

7️⃣ Is it possible to combine projection operators in a single query?


Answer: No, you can't use $ and $elemMatch on the same field in one projection, but
you can apply them separately to different fields.

8️⃣ Why is the _id field returned by default in MongoDB queries, and how do you
exclude it?
Answer: MongoDB includes _id by default. You exclude it by adding { _id: 0 } in the
projection.

🔸 Practical Viva Questions


1️⃣ Write a query to display only the first matching score of 90 from the scores
array.
Answer:

js
Copy
Edit
db.students.find(
{ scores: 90 },
{ "scores.$": 1, _id: 0 }
)
2️⃣ Write a query to display only the subject: "Math" subdocument from the scores
array.
Answer:

js
Copy
Edit
db.students.find(
{},
{ name: 1, scores: { $elemMatch: { subject: "Math" } }, _id: 0 }
)
3️⃣ Write a query to display only the first 3 comments from a comments array.
Answer:

js
Copy
Edit
db.blog.find(
{},
{ title: 1, comments: { $slice: 3 }, _id: 0 }
)
4️⃣ How would you retrieve the last 2 comments using $slice?
Answer:

js
Copy
Edit
db.blog.find(
{},
{ comments: { $slice: -2 }, _id: 0 }
)
5️⃣ Can $elemMatch be used to retrieve multiple matching elements in an array?
Answer: No, $elemMatch returns only the first matching element based on the
criteria in the projection.
Explanation: Aggregation Operations in MongoDB
MongoDB’s Aggregation Framework is a powerful tool for processing data records and
returning computed results. It works by passing documents through a pipeline of
stages, each performing a specific operation.

Common Aggregation Operators:

Operator Purpose
$avg Calculates the average value of a numeric field
$min Returns the minimum value from a group
$max Returns the maximum value from a group
$push Adds values to an array (including duplicates)
$addToSet Adds unique values to an array (no duplicates)

📌 Example Aggregation Queries


Example Collection:

js
Copy
Edit
db.students.insertMany([
{ name: "Ankit", course: "BCA", marks: 80 },
{ name: "Sneha", course: "BCA", marks: 85 },
{ name: "Raj", course: "MCA", marks: 90 },
{ name: "Neha", course: "MCA", marks: 75 },
{ name: "Priya", course: "BCA", marks: 92 }
])
🔸 $avg Example:
js
Copy
Edit
db.students.aggregate([
{ $group: { _id: "$course", avgMarks: { $avg: "$marks" } } }
])
🔸 $min Example:
js
Copy
Edit
db.students.aggregate([
{ $group: { _id: "$course", minMarks: { $min: "$marks" } } }
])
🔸 $max Example:
js
Copy
Edit
db.students.aggregate([
{ $group: { _id: "$course", maxMarks: { $max: "$marks" } } }
])
🔸 $push Example:
js
Copy
Edit
db.students.aggregate([
{ $group: { _id: "$course", studentNames: { $push: "$name" } } }
])
🔸 $addToSet Example:
js
Copy
Edit
db.students.aggregate([
{ $group: { _id: "$course", uniqueNames: { $addToSet: "$name" } } }
])
📌 Viva Questions for Lab Practical (Conceptual + Practical)
🔸 Conceptual Viva Questions
1️⃣ What is the purpose of the Aggregation Framework in MongoDB?
Answer: To process and transform data records into computed results using a
pipeline of stages.

2️⃣ How does the $group stage work in an aggregation pipeline?


Answer: It groups documents by a specified identifier and allows you to perform
aggregation operations like $avg, $min, $max, $push, and $addToSet on grouped data.

3️⃣ What is the difference between $push and $addToSet in MongoDB aggregation?
Answer:

$push adds values to an array, including duplicates.

$addToSet adds only unique values to an array.

4️⃣ Which operator would you use to find the average value of a numeric field?
Answer: $avg

5️⃣ Can you use multiple aggregation operators in a single $group stage?
Answer: Yes, multiple operators like $avg, $max, $min can be used together within
the same $group stage.

6️⃣ What is the role of _id inside the $group stage?


Answer: It acts as the grouping key — documents with the same _id value are grouped
together.

7️⃣ How is $min different from $max?


Answer:

$min returns the smallest value in a group.

$max returns the largest value in a group.

8️⃣ Can $addToSet handle duplicate values in an array?


Answer: No, it ensures that only unique values are added to the resulting array.

9️⃣ What is the output data type of $avg when applied to numeric fields?
Answer: A decimal or double representing the average value.

0️⃣ In what real-world scenario would you prefer $addToSet over $push?
1
Answer: When you need to collect unique items from grouped records, like listing
unique courses or cities from a dataset.

🔸 Practical Viva Questions


1️⃣ Write a query to calculate the average marks of students for each course.
js
Copy
Edit
db.students.aggregate([
{ $group: { _id: "$course", avgMarks: { $avg: "$marks" } } }
])
2️⃣ Write a query to find the highest marks obtained in each course.

js
Copy
Edit
db.students.aggregate([
{ $group: { _id: "$course", maxMarks: { $max: "$marks" } } }
])
3️⃣ Write a query to list all student names enrolled in each course (including
duplicates).

js
Copy
Edit
db.students.aggregate([
{ $group: { _id: "$course", studentNames: { $push: "$name" } } }
])
4️⃣ Write a query to list unique student names enrolled in each course.

js
Copy
Edit
db.students.aggregate([
{ $group: { _id: "$course", uniqueNames: { $addToSet: "$name" } } }
])
5️⃣ Write a query to find the minimum marks scored in each course.

js
Copy
Edit
db.students.aggregate([
{ $group: { _id: "$course", minMarks: { $min: "$marks" } } }
])
Explanation: Aggregation Pipeline in MongoDB
The Aggregation Pipeline processes documents in a collection by passing them
through a sequence of stages. Each stage transforms the documents as they pass
through the pipeline.

📌 Common Aggregation Stages You Asked For:


Stage Purpose
$match Filters documents based on given criteria (like find)
$group Groups documents by a key and performs aggregation operations
$sort Sorts the documents by a specified field
$project Reshapes each document, including or excluding fields, and can compute
new fields
$skip Skips a specified number of documents in the pipeline

📌 Example Collection:
js
Copy
Edit
db.students.insertMany([
{ name: "Ankit", course: "BCA", marks: 80 },
{ name: "Sneha", course: "BCA", marks: 85 },
{ name: "Raj", course: "MCA", marks: 90 },
{ name: "Neha", course: "MCA", marks: 75 },
{ name: "Priya", course: "BCA", marks: 92 }
])
📌 Example Aggregation Pipeline Queries:
1️⃣ $match
js
Copy
Edit
{ $match: { course: "BCA" } }
2️⃣ $group
js
Copy
Edit
{ $group: { _id: "$course", avgMarks: { $avg: "$marks" } } }
3️⃣ $sort
js
Copy
Edit
{ $sort: { marks: -1 } }
4️⃣ $project
js
Copy
Edit
{ $project: { _id: 0, name: 1, course: 1, marks: 1 } }
5️⃣ $skip
js
Copy
Edit
{ $skip: 2 }
📌 Complete Aggregation Pipeline Example:
js
Copy
Edit
db.students.aggregate([
{ $match: { course: "BCA" } },
{ $sort: { marks: -1 } },
{ $project: { _id: 0, name: 1, marks: 1 } },
{ $skip: 1 },
{ $group: { _id: null, avgMarks: { $avg: "$marks" } } }
])
📌 Viva Questions for Lab Practical (Conceptual + Practical)
🔸 Conceptual Viva Questions
1️⃣ What is an Aggregation Pipeline in MongoDB?
Answer: A framework that processes data records through a series of transformation
stages, returning computed results.

2️⃣ What is the function of the $match stage in an aggregation pipeline?


Answer: Filters documents to pass only those that match specified criteria to the
next stage.

3️⃣ How does $group work in the aggregation pipeline?


Answer: Groups input documents by a specified identifier and performs aggregation
operations like $sum, $avg, $max, $min.

4️⃣ What is the purpose of $sort in an aggregation pipeline?


Answer: Sorts documents by one or more fields in ascending (1) or descending (-1)
order.

5️⃣ How does the $project stage work in MongoDB aggregation?


Answer: Reshapes documents, deciding which fields to include, exclude, or compute
new fields for the output.

6️⃣ What is the role of $skip in an aggregation pipeline?


Answer: Skips the specified number of documents in the result set before passing
the remaining documents to the next stage.

7️⃣ Can you combine multiple stages in a single aggregation pipeline?


Answer: Yes, you can combine any number of stages sequentially to form a pipeline.

8️⃣ Why is the order of stages important in an aggregation pipeline?


Answer: Because each stage operates on the results of the previous stage; incorrect
order can produce unintended results.

9️⃣ Can $project stage be used to compute new fields in a document?


Answer: Yes, it can compute new fields using expressions and existing fields.

0️⃣ What are the advantages of using aggregation pipelines over simple queries?
1
Answer: They allow for advanced data transformation, filtering, grouping, and
summarizing in a single operation, reducing multiple query calls.

🔸 Practical Viva Questions


1️⃣ Write an aggregation pipeline to filter students from "BCA" course.

js
Copy
Edit
db.students.aggregate([ { $match: { course: "BCA" } } ])
2️⃣ Write a pipeline to find the average marks per course.

js
Copy
Edit
db.students.aggregate([ { $group: { _id: "$course", avgMarks: { $avg:
"$marks" } } } ])
3️⃣ Write a pipeline to sort students by marks in descending order.

js
Copy
Edit
db.students.aggregate([ { $sort: { marks: -1 } } ])
4️⃣ Write a pipeline to show only name and marks fields in the result.

js
Copy
Edit
db.students.aggregate([ { $project: { _id: 0, name: 1, marks: 1 } } ])
5️⃣ Write a pipeline to skip the first 2 documents from a sorted result.

js
Copy
Edit
db.students.aggregate([
{ $sort: { marks: -1 } },
{ $skip: 2 }
])
6️⃣ Combine $match, $sort, $project, $skip, and $group stages in a pipeline to
compute average marks for students of "BCA" after skipping the top scorer.

js
Copy
Edit
db.students.aggregate([
{ $match: { course: "BCA" } },
{ $sort: { marks: -1 } },
{ $skip: 1 },
{ $group: { _id: null, avgMarks: { $avg: "$marks" } } }
])
7️⃣ What happens if you use $skip before $sort in a pipeline?
Answer: It would skip documents before sorting them, leading to potentially
incorrect final results.

8️⃣ Can $project be used without $match in a pipeline?


Answer: Yes, $project can be used independently or in combination with other
stages.

9️⃣ How can you rename a field using $project in a pipeline?


Answer: By creating a new field in $project and assigning it the value of an
existing field.
Example:

js
Copy
Edit
{ $project: { studentName: "$name" } }
0️⃣
1 Is it possible to use aggregation pipelines for real-time data analytics in
MongoDB?
Answer: Yes, aggregation pipelines are efficient and designed for summarizing and
transforming real-time data.

Explanation & Example Queries


🔸 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
📌 Example Collection (listingsAndReviews)

js
Copy
Edit
{
listing_url: "https://example.com/listing/123",
name: "Cozy Apartment",
address: {
country: "India",
city: "Mumbai"
},
host: {
host_picture_url: "https://example.com/hostpic/123"
}
}
📌 Query:

js
Copy
Edit
db.listingsAndReviews.find(
{ "host.host_picture_url": { $exists: true, $ne: null } },
{
_id: 0,
listing_url: 1,
name: 1,
address: 1,
"host.host_picture_url": 1
}
)
✅ Explanation:

$exists: true ensures the field exists

$ne: null ensures it is not null

The projection part specifies which fields to return

🔸 b. Using E-commerce collection, write a query to display reviews summary


📌 Example Collection (ecommerce)

js
Copy
Edit
{
product_id: 101,
product_name: "Smartphone",
reviews: [
{ user: "Ankit", rating: 4, comment: "Good product" },
{ user: "Sneha", rating: 5, comment: "Excellent" },
{ user: "Neha", rating: 3, comment: "Average" }
]
}
📌 Query:

js
Copy
Edit
db.ecommerce.aggregate([
{ $unwind: "$reviews" },
{
$group: {
_id: "$product_name",
totalReviews: { $sum: 1 },
avgRating: { $avg: "$reviews.rating" },
minRating: { $min: "$reviews.rating" },
maxRating: { $max: "$reviews.rating" }
}
}
])
✅ Explanation:

$unwind breaks the reviews array into separate documents

$group aggregates data by product name

$sum, $avg, $min, $max calculate review statistics

📌 Viva Questions for Lab Practical (Conceptual + Practical)


🔸 Conceptual Viva Questions
1️⃣ What does $exists operator do in a MongoDB query?
Answer: Checks if a specified field exists in a document.

2️⃣ How can you check for a non-null field value in MongoDB?
Answer: Use $exists: true and $ne: null together.

3️⃣ What is the purpose of $unwind in an aggregation pipeline?


Answer: Deconstructs an array field from the input documents to output one document
for each element.

4️⃣ Why would you use $group after $unwind in an aggregation?


Answer: To perform aggregate calculations like count, average, min, max, etc.,
after breaking an array into individual documents.

5️⃣ What operators can you use inside $group to summarize reviews?
Answer: $sum, $avg, $min, $max

6️⃣ How do you project specific fields in a query result in MongoDB?


Answer: By specifying the fields with 1 to include and 0 to exclude in the
projection part of a find() query.

7️⃣ Can you exclude the _id field from query results? How?
Answer: Yes, by adding { _id: 0 } in the projection.

8️⃣ What is the difference between $sum: 1 and $sum: "$field" in $group stage?
Answer:

$sum: 1 counts the number of documents

$sum: "$field" sums the values of a specified field

9️⃣ Why is $unwind necessary before aggregating array elements?


Answer: Because aggregate functions in $group operate on individual documents, not
arrays.

0️⃣ What happens if you don’t use $unwind before $group when summarizing reviews?
1
Answer: The entire reviews array is treated as a single value, and you can't
perform aggregate operations on individual review elements.

🔸 Practical Viva Questions


1️⃣ Write a query to find all listings with a host picture URL in the
listingsAndReviews collection.

js
Copy
Edit
db.listingsAndReviews.find(
{ "host.host_picture_url": { $exists: true, $ne: null } },
{ _id: 0, listing_url: 1, name: 1, address: 1, "host.host_picture_url": 1 }
)
2️⃣ Write a query to display total reviews for each product in the ecommerce
collection.

js
Copy
Edit
db.ecommerce.aggregate([
{ $unwind: "$reviews" },
{ $group: { _id: "$product_name", totalReviews: { $sum: 1 } } }
])
3️⃣ Write a query to calculate the average rating of reviews for each product.

js
Copy
Edit
db.ecommerce.aggregate([
{ $unwind: "$reviews" },
{ $group: { _id: "$product_name", avgRating: { $avg: "$reviews.rating" } } }
])
4️⃣ Write a query to find the highest rating given to any product.

js
Copy
Edit
db.ecommerce.aggregate([
{ $unwind: "$reviews" },
{ $group: { _id: "$product_name", maxRating: { $max: "$reviews.rating" } } }
])
5️⃣ Write a query to find the minimum rating for each product.

js
Copy
Edit
db.ecommerce.aggregate([
{ $unwind: "$reviews" },
{ $group: { _id: "$product_name", minRating: { $min: "$reviews.rating" } } }
])
Explanation & Example Queries
🔸 a. Demonstrate Creation of Different Types of Indexes on a Collection
MongoDB uses indexes to improve the performance of search queries by reducing the
number of documents it needs to scan.

📌 Types of Indexes:
Type Description Example
Unique Index Ensures all values in the indexed field are unique { unique:
true }
Sparse Index Only indexes documents that contain the indexed field { sparse:
true }
Compound Index Indexes multiple fields in a single index { field1: 1, field2: -
1 }
Multikey Index Indexes array fields so each element is indexed Automatically
created when an array field is indexed

📌 Example Collection:
js
Copy
Edit
db.students.insertMany([
{ name: "Ankit", email: "[email protected]", marks: 80, subjects: ["Math",
"Science"] },
{ name: "Sneha", email: "[email protected]", marks: 85, subjects: ["English",
"Science"] },
{ name: "Raj", email: null, marks: 90 }
])
📌 Index Creation Examples:
1️⃣ Unique Index

js
Copy
Edit
db.students.createIndex({ email: 1 }, { unique: true })
2️⃣ Sparse Index

js
Copy
Edit
db.students.createIndex({ email: 1 }, { sparse: true })
3️⃣ Compound Index

js
Copy
Edit
db.students.createIndex({ name: 1, marks: -1 })
4️⃣ Multikey Index

js
Copy
Edit
db.students.createIndex({ subjects: 1 })
✅ Note: Automatically becomes multikey if the field is an array.

🔸 b. Demonstrate Optimization of Queries Using Indexes


Without Index: MongoDB performs a collection scan (scanning every document).

With Index: MongoDB performs an index scan, accessing only relevant documents,
improving speed.

📌 Use explain() to check query performance:

js
Copy
Edit
db.students.find({ email: "[email protected]" }).explain("executionStats")
✅ If an index exists on email, MongoDB uses it — reducing nReturned vs.
totalDocsExamined.

📌 Viva Questions for Lab Practical (Conceptual + Practical)


🔸 Conceptual Viva Questions
1️⃣ What is the purpose of an index in MongoDB?
Answer: To improve the performance of queries by reducing the number of documents
MongoDB needs to scan.

2️⃣ What is a unique index?


Answer: An index that ensures no two documents have the same value for the indexed
field.

3️⃣ What is a sparse index?


Answer: An index that only includes documents where the indexed field exists and is
not null.

4️⃣ What is a compound index?


Answer: An index that includes multiple fields in a specified order to optimize
queries using those fields.

5️⃣ What is a multikey index?


Answer: An index that is created when an array field is indexed, allowing queries
to efficiently search within arrays.
6️⃣ Can you create multiple indexes on the same collection?
Answer: Yes, a collection can have multiple indexes on different fields.

7️⃣ How can you check which index a query uses?


Answer: By using the explain("executionStats") method.

8️⃣ What is the difference between collection scan and index scan?
Answer:

Collection scan — scans every document in the collection.

Index scan — scans only the index entries relevant to the query.

9️⃣ What happens if a unique index is applied to a field with duplicate values?
Answer: The index creation fails and MongoDB returns an error.

🔟 How does a sparse index differ from a regular index?


Answer: A sparse index only includes documents where the indexed field exists; a
regular index includes all documents.

🔸 Practical Viva Questions


1️⃣ Write a command to create a unique index on the email field.

js
Copy
Edit
db.students.createIndex({ email: 1 }, { unique: true })
2️⃣ Write a command to create a sparse index on the email field.

js
Copy
Edit
db.students.createIndex({ email: 1 }, { sparse: true })
3️⃣ Write a command to create a compound index on name (ascending) and marks
(descending).

js
Copy
Edit
db.students.createIndex({ name: 1, marks: -1 })
4️⃣ Write a command to create a multikey index on the subjects array field.

js
Copy
Edit
db.students.createIndex({ subjects: 1 })
5️⃣ How would you check query performance statistics for a query searching by email?

js
Copy
Edit
db.students.find({ email: "[email protected]" }).explain("executionStats")
6️⃣ How would you drop an index on the email field?

js
Copy
Edit
db.students.dropIndex({ email: 1 })
7️⃣ If you query for documents with email: null, will a sparse index on email include
those documents?
Answer: No, sparse indexes exclude documents where the indexed field is missing or
null.

8️⃣ Will a multikey index index every element in an array field?


Answer: Yes, each element in the array is indexed individually.

9️⃣ How would you list all indexes created on a collection?

js
Copy
Edit
db.students.getIndexes()
🔟 Can you create a compound index on an array field and another field?
Answer: No, MongoDB does not allow compound indexes that include both array fields
and other fields unless specific constraints are met.

Explanation & Example Queries


🔸 a. Develop a Query to Demonstrate Text Search using Catalog Data Collection for a
Given Word
📌 Step 1: Create a Text Index

To perform text search, you must create a text index on one or more fields.

Example Collection (catalog):

js
Copy
Edit
db.catalog.insertMany([
{ item: "Smartphone", description: "Latest Android smartphone with fast
processor" },
{ item: "Laptop", description: "Lightweight laptop for office and home use" },
{ item: "Tablet", description: "Portable tablet for reading and browsing" }
])
Create a text index on description

js
Copy
Edit
db.catalog.createIndex({ description: "text" })
📌 Step 2: Perform Text Search for a Given Word

Example: Search for documents containing the word "smartphone"

js
Copy
Edit
db.catalog.find({ $text: { $search: "smartphone" } })
✅ Explanation:
This query returns all documents where the text index matches the word "smartphone"
in the description field.

🔸 b. Develop Queries to Illustrate Excluding Documents with Certain Words and


Phrases
Example: Exclude documents containing the word "tablet"

js
Copy
Edit
db.catalog.find({ $text: { $search: "-tablet" } })
✅ Explanation:
The - (minus) sign before a word excludes documents containing that word.

Example: Exclude documents containing both "laptop" and "smartphone"

js
Copy
Edit
db.catalog.find({ $text: { $search: "-laptop -smartphone" } })
✅ Explanation:
This query excludes documents containing either "laptop" or "smartphone".

Important:

Text search is case-insensitive.

Text search requires a text index.

You can combine positive and negative words like:

js
Copy
Edit
$text: { $search: "smartphone -tablet" }
📌 Viva Questions for Lab Practical (Conceptual + Practical)
🔸 Conceptual Viva Questions
1️⃣ What is a text index in MongoDB?
Answer: A special index type that supports text search queries on string content in
one or more fields.

2️⃣ How do you create a text index on a field?


Answer: Using the createIndex() method with "text" as the index type.
Example:

js
Copy
Edit
db.collection.createIndex({ fieldName: "text" })
3️⃣ What does the $text operator do in a MongoDB query?
Answer: Performs a text search on fields indexed with a text index.

4️⃣ Is MongoDB text search case-sensitive?


Answer: No, text search is case-insensitive by default.

5️⃣ How can you exclude documents containing a certain word in a text search?
Answer: By adding a minus (-) before the word in the $search string.

6️⃣ Can you perform text search without creating a text index?
Answer: No, a text index is required for text search queries.

7️⃣ How would you perform a text search for multiple words?
Answer: By separating the words with spaces in the $search string.

Example:

js
Copy
Edit
$text: { $search: "smartphone laptop" }
8️⃣ What happens if you search for a word not present in any document?
Answer: The query returns an empty result set.

9️⃣ Can you combine positive and negative words in a single text search?
Answer: Yes. Example:

js
Copy
Edit
$text: { $search: "smartphone -tablet" }
finds documents containing "smartphone" but not "tablet".

🔟 Which fields will be included in a text index when creating one on multiple
fields?
Answer: Only the fields explicitly specified during the createIndex() call.

🔸 Practical Viva Questions


1️⃣ Write a command to create a text index on the description field of a catalog
collection.

js
Copy
Edit
db.catalog.createIndex({ description: "text" })
2️⃣ Write a query to find all catalog items containing the word "smartphone".

js
Copy
Edit
db.catalog.find({ $text: { $search: "smartphone" } })
3️⃣ Write a query to find all catalog items excluding the word "tablet".

js
Copy
Edit
db.catalog.find({ $text: { $search: "-tablet" } })
4️⃣ Write a query to find all catalog items containing "smartphone" but not "tablet".

js
Copy
Edit
db.catalog.find({ $text: { $search: "smartphone -tablet" } })
5️⃣ Write a query to find all catalog items excluding both "laptop" and "smartphone".

js
Copy
Edit
db.catalog.find({ $text: { $search: "-laptop -smartphone" } })
6️⃣ How would you list all indexes present on the catalog collection?

js
Copy
Edit
db.catalog.getIndexes()
7️⃣ How do you remove an existing text index from a collection?
js
Copy
Edit
db.catalog.dropIndex("description_text")
✅ (Replace "description_text" with the actual index name.)

8️⃣ Can you have multiple text indexes on different fields in the same collection?
Answer: No, MongoDB only allows one text index per collection. However, that text
index can include multiple fields.

9️⃣ How can you check if a text index exists before running a text search?
Answer: By using getIndexes() to list all existing indexes.

🔟 Is it possible to sort results by text search relevance score?


Answer: Yes, by projecting the text score using $meta: "textScore" and sorting by
it.

Example:

js
Copy
Edit
db.catalog.find(
{ $text: { $search: "smartphone" } },
{ score: { $meta: "textScore" } }
).sort({ score: { $meta: "textScore" } })
program 10
1. Can you explain what an aggregation pipeline is in MongoDB and its typical use
cases?
2. How does text search work in MongoDB?
3. What are the key stages you would include in an aggregation pipeline to perform
a text search on a catalog collection?
4. How would you create a text index on the catalog collection to enable text
search?
5. Can you write a sample aggregation pipeline query to search for a specific
keyword in the catalog?
6. How would you sort the results based on text search relevance?
7. How can you include additional filtering criteria in the aggregation pipeline
along with the text search?
8. What are some limitations or considerations when using text search in MongoDB?
9. How would you handle searching across multiple fields in the catalog?
10. Can you describe how to return only specific fields from the catalog documents
in the results?
11. How would you optimize the aggregation pipeline for performance when dealing
with large catalog data?
12. Explain how to use the `$meta` operator in the context of text search
aggregation.
13. How can you combine text search with other types of queries in an aggregation
pipeline?
14. What are some common errors or pitfalls to avoid when implementing text search
in an aggregation pipeline?
15. How would you update the aggregation pipeline to support fuzzy or partial
matching in text search?

You might also like