The collection of intermediate-level questions presented earlier serves as a rich resource for self-assessment, interview preparation, and coding practice. Each question comes with a concise explanation and a code snippet, offering a practical understanding of various MongoDB operations and features. Explore how you can utilize these questions to gauge your MongoDB skills, prepare for interviews, and improve your coding prowess.
50+ Mongodb Intermediate Interview questions and answers
Describe MongoDB’s replication feature and demonstrate how to set up a replica set.
Replication in MongoDB provides redundancy and increases data availability. It’s achieved through replica sets, which consist of multiple MongoDB instances.
mongod --replSet "rs0" --dbpath /srv/mongodb/rs0 --port 27017
Explain the role of the mongos and mongod processes in a MongoDB sharded cluster.
mongod is the primary daemon process for the MongoDB system, handling data requests and managing data access. mongos acts as a routing service for MongoDB sharded clusters, directing client requests to the appropriate shard.
mongos --configdb configReplSet/configdb0:27019
Demonstrate how to use the $match operator in an aggregation pipeline.
The $match operator filters documents to pass only those that match the specified condition(s) to the next pipeline stage.
db.collection.aggregate([ { $match: { age: { $gte: 21 } } } ])
Explain the use of upsert in MongoDB and provide a code example.
The upsert option creates a new document if the query does not match any existing documents.
db.collection.update(
{ _id: 1 },
{ $set: { name: "new name" } },
{ upsert: true }
)
Explain the use of the $group operator in MongoDB’s Aggregation Framework and provide an example.
The $group operator groups documents by specified expression(s) and computes aggregate values based on the collection of grouped documents.
db.orders.aggregate([
{ $group : { _id : "$cust_id", total : { $sum : "$amount" }}}
])
How would you perform a text search in MongoDB? Provide a code snippet.
To perform text search, create a text index on the field(s) and use the $text operator.
db.collection.createIndex({ field: "text" })
db.collection.find({ $text: { $search: "query" }})
Demonstrate how to use the $push operator within an update operation.
The $push operator appends a specified value to an array.
db.collection.update({ _id: 1 }, { $push: { scores: 89 }})
Explain the concept of cursor in MongoDB and provide an example.
A cursor in MongoDB is a pointer to the result set of a query, which can be iterated to access documents.
var cursor = db.collection.find();
while ( cursor.hasNext() ) { printjson( cursor.next() ); }
Describe how to use the explain() method to analyze a query’s performance.
The explain() method provides information about the execution plan of a query.
db.collection.find({ field: value }).explain("executionStats")
Demonstrate how to use the $addToSet operator with an example.
The $addToSet operator adds a value to an array only if the value is not already present.
db.collection.update({ _id: 1 }, { $addToSet: { tags: "new tag" }})
Explain the concept of TTL (Time-To-Live) collections in MongoDB and provide an example of how to create one.
TTL collections are used to store documents that expire at a certain time, defined by a TTL index.
db.collection.createIndex({ "lastModified": 1 }, { expireAfterSeconds: 3600 })
How would you handle error checking in a MongoDB operation? Provide a code example.
Error checking can be done by checking the writeConcernError and writeErrors fields in the result object.
var result = db.collection.insert({ _id: 1 });
if(result.writeConcernError || result.writeErrors) { // handle error }
Demonstrate how to use the $slice operator to limit the number of elements in an array field returned by a query.
The $slice operator limits the number of elements projected from an array.
db.collection.find({ _id: 1 }, { arrayField: { $slice: 5 }})
Explain how to use the db.runCommand() method to execute a database command. Provide an example.
The db.runCommand() method allows the execution of specified database commands.
db.runCommand({ collStats: "collection" })
Describe the $merge stage in the MongoDB Aggregation Framework and provide an example.
The $merge stage is used to merge the documents from the aggregation pipeline into a specified collection.
db.orders.aggregate([
{ $match: { status: "A" }},
{ $merge: { into: "warehouse", whenMatched: "merge", whenNotMatched: "insert" }}
])
Explain the use of $inc operator in MongoDB and provide an example.
The $inc operator increments a field by a specified value.
db.collection.update({ _id: 1 }, { $inc: { count: 1 }})
Describe and demonstrate how to use the $bucket stage in the Aggregation Framework.
The $bucket stage categorizes documents into groups, called buckets, based on a specified expression.
db.sales.aggregate([
{ $bucket: { groupBy: "$price", boundaries: [0, 100, 200], default: "Other", output: { count: { $sum: 1 }}}}
])
How would you use the $arrayElemAt operator within an aggregation pipeline? Provide an example.
The $arrayElemAt operator returns the element at the specified array index.
db.collection.aggregate([
{ $project: { firstElem: { $arrayElemAt: ["$arrayField", 0] }}}
])
Explain the use of db.collection.stats() method and provide an example.
The db.collection.stats() method provides statistics about a collection.
db.collection.stats()
Demonstrate how to use the $pull operator to remove elements from an array.
The $pull operator removes all instances of a specified value from an array.
db.collection.update({ _id: 1 }, { $pull: { scores: { $gte: 80 }}})
Explain how to use the $out stage in the Aggregation Framework and provide an example.
The $out stage writes the result of the aggregation pipeline to a specified collection.
db.collection.aggregate([
{ $match: { status: "A" }},
{ $out: "newCollection" }
])
How can you use the $currentDate operator in an update operation? Provide a code example.
he $currentDate operator sets the value of a field to the current date.
db.collection.update({ _id: 1 }, { $currentDate: { lastModified: true }})
Demonstrate how to use the distinct() method to find unique values of a field.
The distinct() method returns a list of distinct values for a specified field.
db.collection.distinct("field")
Explain the use of the $redact stage in the Aggregation Framework and provide an example.
The $redact stage restricts the contents of the documents based on information stored in the documents themselves.
db.employees.aggregate([
{ $redact: { $cond: [{ $eq: ["$$accessLevel", "$requiredAccess"] }, "$$KEEP", "$$PRUNE"] }}
])
Describe the $sample stage in the Aggregation Framework and provide an example.
The $sample stage randomly selects a specified number of documents from its input.
db.collection.aggregate([
{ $sample: { size: 5 }}
])
Explain how to use the $mul operator in an update operation and provide an example.
The $mul operator multiplies the value of a field by a specified amount.
db.collection.update({ _id: 1 }, { $mul: { price: 1.25 }})
Describe and demonstrate the use of the $split operator in the Aggregation Framework.
The $split operator splits a string into an array of substrings based on a delimiter.
db.collection.aggregate([
{ $project: { nameArray: { $split: ["$name", " "] }}}
])
How do you use the db.collection.reIndex() method and why? Provide an example.
The db.collection.reIndex() method rebuilds all indexes on a collection, which can be useful to reclaim disk space or resolve issues.
db.collection.reIndex()
Explain the $min and $max operators in MongoDB and provide an example.
The $min and $max operators update the value of the field to a specified value if the specified value is less or greater, respectively.
db.collection.update({ _id: 1 }, { $min: { lowScore: 70 }, $max: { highScore: 90 }})
💁 Check out our other articles😃
👉 Generate a free Developer Portfolio website with AI prompts
👉 110 Mongodb Beginner Interview question and answers
Demonstrate how to use the db.collection.dropIndex() method with an example.
The db.collection.dropIndex() method removes a specified index from a collection.
db.collection.dropIndex("indexName")
Describe and demonstrate the use of the $map operator in the Aggregation Framework.
The $map operator applies a specified expression to each item in an array and returns an array with the applied results.
db.collection.aggregate([
{ $project: { squaredArray: { $map: { input: "$array", as: "el", in: { $multiply: ["$$el", "$$el"] }}}}}
])
Explain the use of the db.collection.bulkWrite() method and provide an example.
The db.collection.bulkWrite() method allows the execution of a list of write operations in bulk.
db.collection.bulkWrite([
{ insertOne: { document: { _id: 1, name: "John Doe" }}},
{ updateOne: { filter: { _id: 2 }, update: { $set: { name: "Jane Doe" }}, upsert: true }}
])
Demonstrate how to use the $elemMatch operator within a query.
The $elemMatch operator matches documents that contain an array field with at least one element that meets all the specified query criteria.
db.collection.find({ scores: { $elemMatch: { $gte: 80, $lt: 85 }}})
Explain and provide an example of how to use the $lookup operator to perform a left outer join.
The $lookup operator performs a left outer join to another collection in the same database.
db.orders.aggregate([
{ $lookup: { from: "products", localField: "product_id", foreignField: "_id", as: "orderDetails" }}
])
Explain the use of the $regex operator in MongoDB and provide an example.
The $regex operator provides regular expression capabilities for pattern matching strings in queries.
db.collection.find({ name: { $regex: /^Jo/, $options: 'i' }})
Describe and demonstrate the use of the $cond operator in the Aggregation Framework.
The $cond operator returns different values based on a specified condition.
db.collection.aggregate([
{ $project: { status: { $cond: { if: { $gte: ["$score", 70] }, then: "Pass", else: "Fail" }}}}
])
How do you use the db.collection.drop() method and why? Provide an example.
The db.collection.drop() method removes a collection from the database.
db.collection.drop()
Explain the $size operator in MongoDB and provide an example.
The $size operator returns the number of elements in an array.
db.collection.find({ arrayField: { $size: 3 }})
Describe and demonstrate the use of the $type operator within a query.
The $type operator selects documents where a field is of the specified type.
db.collection.find({ field: { $type: "string" }})
Explain how to use the db.collection.createIndex() method with compound indexes and provide an example.
The db.collection.createIndex() method creates an index on a collection, and compound indexes are defined on multiple fields.
db.collection.createIndex({ field1: 1, field2: -1 })
Demonstrate how to use the $unset operator in an update operation.
The $unset operator removes the specified field from a document.
db.collection.update({ _id: 1 }, { $unset: { field: "" }})
Describe and demonstrate the use of the $filter operator in the Aggregation Framework.
The $filter operator selects a subset of an array to return based on a specified condition.
db.collection.aggregate([
{ $project: { filteredArray: { $filter: { input: "$array", as: "item", cond: { $gte: ["$$item", 0] }}}}}
])
Explain the use of the db.collection.countDocuments() method and provide an example.
The db.collection.countDocuments() method returns the count of documents that would match a find() query.
db.collection.countDocuments({ status: "A" })
Demonstrate how to use the $replaceRoot stage in the Aggregation Framework.
The $replaceRoot stage replaces the input document with the specified document.
db.collection.aggregate([
{ $replaceRoot: { newRoot: "$subDocument" }}
])
Explain the $dateToString operator in MongoDB and provide an example.
The $dateToString operator converts a date object to string format.
db.orders.aggregate([
{ $project: { dateString: { $dateToString: { format: "%Y-%m-%d", date: "$orderDate" }}}}
])
Demonstrate how to use the $mergeObjects operator in the Aggregation Framework.
The $mergeObjects operator merges two or more documents into a single document.
db.orders.aggregate([
{ $project: { merged: { $mergeObjects: ["$document1", "$document2"] }}}
])
Explain the db.collection.watch() method and provide an example.
The db.collection.watch() method opens a change stream cursor for a collection to watch for data changes.
const changeStream = db.collection.watch();
changeStream.on('change', (change) => {
console.log(change);
});
Describe and demonstrate the use of the $switch operator in the Aggregation Framework.
The $switch operator evaluates a series of case expressions and returns a result.
db.collection.aggregate([
{ $project: { priceCategory: {
$switch: {
branches: [
{ case: { $lt: ["$price", 20] }, then: "Low" },
{ case: { $lt: ["$price", 50] }, then: "Medium" },
],
default: "High"
}
}}}
])
Explain how to use the db.collection.estimatedDocumentCount() method and provide an example.
The db.collection.estimatedDocumentCount() method provides an estimated count of all documents in the collection.
db.collection.estimatedDocumentCount()
Demonstrate how to use the $subtract operator within an aggregation pipeline.
The $subtract operator subtracts two numbers or dates.
db.collection.aggregate([
{ $project: { difference: { $subtract: ["$field1", "$field2"] }}}
])
Explain the use of the $push operator within the $group stage and provide an example.
Within the $group stage, the $push operator appends the value to an array in the grouped document.
db.collection.aggregate([
{ $group: { _id: "$category", items: { $push: "$$ROOT" }}}
])
Describe and demonstrate the use of the $literal operator in the Aggregation Framework.
The $literal operator returns the specified value without parsing.
db.collection.aggregate([
{ $project: { item: { $literal: "$field" }}}
])
Explain how to use the db.collection.findOneAndUpdate() method and provide an example.
The db.collection.findOneAndUpdate() method updates the first document that matches the query and returns the original or updated document.
db.collection.findOneAndUpdate({ _id: 1 }, { $set: { name: "new name" }}, { returnOriginal: false })
Demonstrate how to use the $arrayToObject operator in the Aggregation Framework.
The $arrayToObject operator converts an array of key-value pairs into an object.
db.collection.aggregate([
{ $project: { object: { $arrayToObject: "$keyValueArray" }}}
])