Viva
Viva
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.
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
📌 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.
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.
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
📌 Example:
js
Copy
Edit
db.students.find({ age: { $gt: 20 } })
👉 Logical Selectors
Combine multiple conditions.
📌 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)
📌 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.
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.
$bitsAnyClear — Matches documents where any of the specified bit positions are 0
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.
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.
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.
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.
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.
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.
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.
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.
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)
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.
3️⃣ What is the difference between $push and $addToSet in MongoDB aggregation?
Answer:
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.
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.
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.
📌 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.
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.
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.
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.
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:
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:
2️⃣ How can you check for a non-null field value in MongoDB?
Answer: Use $exists: true and $ne: null together.
5️⃣ What operators can you use inside $group to summarize reviews?
Answer: $sum, $avg, $min, $max
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:
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.
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.
With Index: MongoDB performs an index scan, accessing only relevant documents,
improving speed.
js
Copy
Edit
db.students.find({ email: "[email protected]" }).explain("executionStats")
✅ If an index exists on email, MongoDB uses it — reducing nReturned vs.
totalDocsExamined.
8️⃣ What is the difference between collection scan and index scan?
Answer:
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.
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.
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.
To perform text search, you must create a text index on one or more fields.
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
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.
js
Copy
Edit
db.catalog.find({ $text: { $search: "-tablet" } })
✅ Explanation:
The - (minus) sign before a word excludes documents containing that word.
js
Copy
Edit
db.catalog.find({ $text: { $search: "-laptop -smartphone" } })
✅ Explanation:
This query excludes documents containing either "laptop" or "smartphone".
Important:
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.
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.
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.
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.
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?