The use command selects the specified database. If the database does not exist, MongoDB creates it when you first store data in that database.
Incorrect! Try again.
6Which method is used to add a single document to a collection?
data manipulation - insert, update, delete, find
Easy
A.db.collection.add()
B.db.collection.insertOne()
C.db.collection.create()
D.db.collection.putOne()
Correct Answer: db.collection.insertOne()
Explanation:
The insertOne() method is the standard command for inserting a single document into a specified collection.
Incorrect! Try again.
7How do you find all documents in a collection named users?
data manipulation - insert, update, delete, find
Easy
A.db.users.select(*)
B.db.users.find({})
C.db.users.fetchAll({})
D.db.users.getAll()
Correct Answer: db.users.find({})
Explanation:
The find() method is used to query a collection for documents. Passing an empty document {} as the query filter matches all documents in the collection.
Incorrect! Try again.
8What is Mongoose?
Introduction to Mongoose
Easy
A.A front-end JavaScript framework
B.A query language for SQL databases
C.A standalone database server
D.An Object Data Modeling (ODM) library for MongoDB and Node.js
Correct Answer: An Object Data Modeling (ODM) library for MongoDB and Node.js
Explanation:
Mongoose provides a straightforward, schema-based solution to model your application data, manage relationships, and provide type casting and validation for MongoDB.
Incorrect! Try again.
9In Mongoose, what is the primary purpose of a Schema?
Schema definition
Easy
A.To create a new database
B.To execute raw database commands
C.To define the structure and properties of documents within a collection
D.To connect to the MongoDB database
Correct Answer: To define the structure and properties of documents within a collection
Explanation:
A Mongoose schema defines the shape of the documents, default values, validators, and other properties for a specific collection.
Incorrect! Try again.
10Once you have a Mongoose schema, what do you need to create to interact with the corresponding MongoDB collection?
Models
Easy
A.A View
B.A Model
C.A Service
D.A Controller
Correct Answer: A Model
Explanation:
Models are constructors compiled from Schema definitions. An instance of a model represents a MongoDB document and can be saved, updated, or deleted.
Incorrect! Try again.
11What does the 'U' in CRUD stand for?
CRUD operations
Easy
A.Undo
B.Update
C.Upload
D.Unify
Correct Answer: Update
Explanation:
CRUD stands for Create, Read, Update, and Delete, which are the four basic functions of persistent storage.
Incorrect! Try again.
12MongoDB documents are stored in a format that is a binary representation of JSON. What is this format called?
Getting familiar with MongoDB documents and collections
Easy
A.XML
B.YML
C.DocDB
D.BSON
Correct Answer: BSON
Explanation:
BSON stands for Binary JSON. It is a binary-encoded serialization of JSON-like documents that MongoDB uses for storing data.
Incorrect! Try again.
13Which command correctly drops a collection named products?
MongoDB shell commands - drop collection, drop database
Easy
A.db.drop(products)
B.drop collection products
C.db.products.drop()
D.db.deleteCollection('products')
Correct Answer: db.products.drop()
Explanation:
The db.collectionName.drop() method is used to remove a collection completely from the database, including any indexes associated with it.
Incorrect! Try again.
14To delete the entire database you are currently using, which command should be run?
MongoDB shell commands - drop collection, drop database
Easy
A.db.drop()
B.deleteAllData()
C.db.admin.drop()
D.db.dropDatabase()
Correct Answer: db.dropDatabase()
Explanation:
The db.dropDatabase() command drops the entire current database, deleting all its collections and indexes.
Incorrect! Try again.
15To modify the first document that matches a filter, which command would you use?
data manipulation - insert, update, delete, find
Easy
A.db.collection.save()
B.db.collection.update()
C.db.collection.modifyOne()
D.db.collection.updateOne()
Correct Answer: db.collection.updateOne()
Explanation:
updateOne() is the specific method for updating a single document that matches the specified filter criteria.
Incorrect! Try again.
16To remove the first document where the status field is "archived", which command is correct?
data manipulation - insert, update, delete, find
Easy
The deleteOne() method takes a filter document as its first argument and deletes the first document it finds that matches the filter.
Incorrect! Try again.
17Which Mongoose function is used to compile a schema into a Model?
Models
Easy
A.mongoose.compile()
B.mongoose.createModel()
C.mongoose.model()
D.mongoose.schema()
Correct Answer: mongoose.model()
Explanation:
The mongoose.model('ModelName', mySchema) function is the correct way to create a Mongoose model from a previously defined schema.
Incorrect! Try again.
18When implementing pagination, which method is used to specify the maximum number of documents a query should return?
Perform pagination
Easy
A..limit()
B..max()
C..size()
D..count()
Correct Answer: .limit()
Explanation:
The .limit(number) method is chained to a find() query to restrict the number of documents returned, which is essential for setting a page size in pagination.
Incorrect! Try again.
19To get the documents for the third page of a list, where each page has 10 items, you would use .skip(20). What is the purpose of .skip()?
Perform pagination
Easy
A.To limit the number of results
B.To ignore a specified number of documents from the beginning of the result set
C.To jump to a specific document ID
D.To skip over documents with errors
Correct Answer: To ignore a specified number of documents from the beginning of the result set
Explanation:
The .skip(number) method controls the starting point of the results set, allowing you to bypass a certain number of documents, which is a core component of pagination logic.
Incorrect! Try again.
20What is a key advantage of MongoDB's flexible schema?
Introduction to MongoDB
Easy
A.It requires all documents to have the exact same fields.
B.It does not allow the data structure to change over time.
C.It allows documents in the same collection to have different fields and structures.
D.It enforces a strict, predefined table structure like SQL.
Correct Answer: It allows documents in the same collection to have different fields and structures.
Explanation:
MongoDB's dynamic and flexible schema means that you do not need to define the structure of documents beforehand, and documents within the same collection can vary, which is great for evolving applications.
Incorrect! Try again.
21In the MongoDB shell, you execute the command use myNewAppDB. At this exact moment, what is the status of the myNewAppDB database on the server?
MongoDB shell commands - create database
Medium
A.The command will fail if the database does not already exist.
B.A database object is created in the shell's memory, but the database is not physically created on disk until the first document is inserted into a collection within it.
C.The database is immediately created on the server's file system, but it is empty.
D.The database and a default 'test' collection are created on the server's file system.
Correct Answer: A database object is created in the shell's memory, but the database is not physically created on disk until the first document is inserted into a collection within it.
Explanation:
MongoDB practices 'lazy creation' for databases. The use <dbname> command switches the current database context in the shell. The database itself is only created on the file system when you first store data in it, for example, by inserting a document into a collection.
Incorrect! Try again.
22You want to update a user's profile. The user document is { "_id": 1, "username": "alex", "status": "active", "profile": { "theme": "dark" } }. Which command will change the status to "inactive" and add a lastLogin field without removing the existing profile object?
Without an update operator like set operator correctly modifies existing fields and adds new ones without affecting other fields in the document.
Incorrect! Try again.
23A collection products contains documents with name, price, and category fields. How would you query for all products in the 'electronics' category that cost more than $500, showing only their name and price?
The correct syntax uses a query document where conditions are implicitly joined by AND. The second argument, called a projection, specifies which fields to include (1 for include, 0 for exclude). _id is included by default, so it must be explicitly excluded with _id: 0 if not desired.
Incorrect! Try again.
24You are defining a Mongoose schema for a blog post which should have a title that is required and unique. Which schema definition is correct?
In Mongoose, schema fields are defined with a type. To add constraints like required and unique, you must use an object for the field definition where the type and constraints are specified as properties. unique: true creates a unique index on that field in the MongoDB collection.
Incorrect! Try again.
25In Mongoose, you execute await Product.findByIdAndUpdate('someId', { $inc: { stock: -1 } }, { new: true });. What is the primary purpose of the { new: true } option?
CRUD operations
Medium
A.It creates a new document if one with the given ID is not found.
B.It validates the update operation against the schema before executing.
C.It forces the creation of a new document, ignoring the provided ID.
D.It returns the document as it was after the update has been applied.
Correct Answer: It returns the document as it was after the update has been applied.
Explanation:
By default, findByIdAndUpdate and findOneAndUpdate return the document as it was before the update was applied. Setting the { new: true } option configures the method to return the modified document instead.
Incorrect! Try again.
26You need to implement pagination in a Mongoose query to display the 5th page of results, with each page containing 20 items. Which combination of .skip() and .limit() methods should be used?
Perform pagination
Medium
A..limit(5).skip(20)
B..skip(5).limit(20)
C..limit(20).skip(80)
D..skip(100).limit(20)
Correct Answer: .limit(20).skip(80)
Explanation:
To get the Nth page, you need to skip (N-1) * itemsPerPage documents. In this case, for the 5th page with 20 items per page, the number of documents to skip is (5 - 1) * 20 = 80. The .limit(20) method then retrieves the next 20 documents.
Incorrect! Try again.
27A collection articles has documents that may or may not have a tags array. You want to add the tag 'featured' to an article with _id: 123, but only if 'featured' is not already in the tags array. Which update operation is most appropriate?
The push would add the tag regardless of whether it's already present.
Incorrect! Try again.
28When you define a Mongoose model like const User = mongoose.model('User', userSchema);, what is the conventional name of the MongoDB collection that Mongoose will interact with by default?
Models
Medium
A.'user'
B.'user_collection'
C.'User'
D.'users'
Correct Answer: 'users'
Explanation:
Mongoose follows a convention of taking the singular model name you provide (e.g., 'User'), making it lowercase, and pluralizing it to determine the collection name. Therefore, the 'User' model will map to the 'users' collection.
Incorrect! Try again.
29You are using db.products.insertMany([...], { ordered: false }) to insert 100 documents. A validation error occurs on the 50th document. What will be the outcome of the operation?
Data manipulation - insert
Medium
A.The server attempts to insert all 100 documents, skipping the 50th one, and reports errors for any that fail.
B.Only the 50th document fails; the other 99 are guaranteed to be inserted successfully.
C.The first 49 documents are inserted, and the operation stops.
D.The entire operation fails, and no documents are inserted.
Correct Answer: The server attempts to insert all 100 documents, skipping the 50th one, and reports errors for any that fail.
Explanation:
The { ordered: false } option tells MongoDB to continue trying to insert the remaining documents in the batch even if one fails. The default behavior (ordered: true) is to stop the entire operation upon the first error.
Incorrect! Try again.
30What is a key difference between Model.findById('someId') and Model.findOne({ _id: 'someId' }) in Mongoose?
CRUD operations
Medium
A.findById can only query by _id, while findOne can use any field.
B.There is no functional difference; findById is just a shorthand.
C.findById is faster because it bypasses schema validation.
D.findById returns a full document while findOne returns only the _id.
Correct Answer: There is no functional difference; findById is just a shorthand.
Explanation:
In Mongoose, Model.findById(id) is essentially a convenient shorthand for Model.findOne({ _id: id }). They both perform the same underlying query and return the same result. The choice between them is a matter of code readability and convenience.
Incorrect! Try again.
31In the context of MongoDB, how does a document relate to a collection?
MongoDB Terminology - database, collection, document and files
Medium
A.A document is a metadata file that describes the indexes of a collection.
B.A document is a single record within a collection, analogous to a row in a relational table.
C.A document is a schema that defines the structure of a collection.
D.A document is a container for multiple collections, similar to a database.
Correct Answer: A document is a single record within a collection, analogous to a row in a relational table.
Explanation:
The core terminology mapping from relational databases to MongoDB is: Database -> Database, Table -> Collection, and Row/Record -> Document. Each document is a BSON (Binary JSON) object that holds the data for a single entity.
Incorrect! Try again.
32Your logs collection has 1000 documents where the level field is 'DEBUG'. If you run the command db.logs.deleteOne({ level: 'DEBUG' }), what will be the result?
Data manipulation - delete
Medium
A.Exactly one document matching the filter will be deleted, typically the first one found by the database.
B.All 1000 'DEBUG' log documents will be deleted.
C.The command will fail because it matched more than one document.
D.A random 'DEBUG' log document will be deleted.
Correct Answer: Exactly one document matching the filter will be deleted, typically the first one found by the database.
Explanation:
As its name implies, deleteOne is designed to delete only a single document. Even if the query filter matches multiple documents, it will only delete the first one it encounters. To delete all matching documents, you would use deleteMany.
Incorrect! Try again.
33How would you define a field in a Mongoose schema that must be a string from a predefined list of values, such as 'pending', 'processing', or 'complete'?
Mongoose's enum validator is used for this purpose. It is defined as a property within the field's definition object and takes an array of allowed string values. Any attempt to save a document with a value for this field that is not in the array will result in a validation error.
Incorrect! Try again.
34You attempt to update a document that does not exist using db.metrics.updateOne({ date: '2023-10-26' }, { $inc: { visits: 1 } }). The document is not found and nothing happens. How can you modify this command to create the document with visits: 1 if it doesn't exist?
Data manipulation - update
Medium
A.Add the { upsert: true } option.
B.Add the { create: true } option.
C.Add the { new: true } option.
D.Use the updateAndInsertOne() command instead.
Correct Answer: Add the { upsert: true } option.
Explanation:
The upsert option (a blend of 'update' and 'insert') instructs MongoDB to perform an update if a document matching the query filter is found, or to insert a new document if no matching document is found. The new document will be a combination of the query filter and the update operation.
Incorrect! Try again.
35What is the primary advantage of using Mongoose, an Object Data Modeling (ODM) library, over the native MongoDB driver in a Node.js application?
Introduction to Mongoose
Medium
A.Mongoose provides a direct performance increase, making all database queries faster.
B.Mongoose translates MongoDB queries into SQL, allowing developers to use familiar syntax.
C.Mongoose is the only way to connect a Node.js application to a MongoDB database.
D.Mongoose provides schema definition and validation, type casting, and business logic hooks, which are not present in the native driver.
Correct Answer: Mongoose provides schema definition and validation, type casting, and business logic hooks, which are not present in the native driver.
Explanation:
The native driver provides a direct, low-level connection to MongoDB. Mongoose is a layer on top of the driver that provides a powerful schema-based modeling environment. This helps enforce data structure, validate data before it's saved, and provides middleware (hooks) for business logic, significantly improving development workflow and data integrity.
Incorrect! Try again.
36You have two collections: users and users_temp. What is the result of running db.getCollection('users_temp').drop() in the MongoDB shell?
MongoDB shell commands - drop collection
Medium
A.It renames the users_temp collection to users_temp_dropped.
B.It empties the users_temp collection but keeps the collection and its indexes.
C.It drops the users_temp collection and all of its indexes permanently.
D.It drops both the users and users_temp collections.
Correct Answer: It drops the users_temp collection and all of its indexes permanently.
Explanation:
The drop() command on a collection is a destructive operation that completely removes the collection, all documents within it, and any associated indexes. The db.getCollection() syntax is a safe way to reference collection names that might be invalid as JavaScript properties (e.g., names with hyphens).
Incorrect! Try again.
37In a Mongoose model named Comment, how would you efficiently count the total number of comments where the isApproved field is true?
Comment.countDocuments() is the modern and recommended Mongoose method for counting documents that match a query. While find().length works, it is inefficient because it retrieves all matching documents from the database into memory just to count them. countDocuments performs the count on the database server itself, which is much more efficient. count() is deprecated.
Incorrect! Try again.
38When building a paginated API endpoint, what is the most robust way to handle both the paginated results and the total number of documents matching the query?
Perform pagination
Medium
A.First, run a find() query with .skip() and .limit(). Then, in the application, use the length of the returned array as the total.
B.Use an aggregation pipeline with $facet to get both the count and the paginated data in a single database call.
C.Run two separate queries: one find() with .skip() and .limit() for the data, and another countDocuments() with the same filter for the total count.
D.Run a single find() query without pagination, get the total count from the result's length, then slice the array in the application code.
Correct Answer: Use an aggregation pipeline with $facet to get both the count and the paginated data in a single database call.
Explanation:
While running two separate queries is a common and valid approach, using the $facet aggregation stage is often more efficient. It allows you to process multiple aggregation pipelines within a single stage on the same set of input documents. This lets you get the total count and the paginated subset of data with a single round trip to the database, which can be more performant.
Incorrect! Try again.
39Which of the following statements is true regarding schemas in MongoDB collections?
Getting familiar with MongoDB documents and collections
Medium
A.A schema must be defined for a collection before any documents can be inserted.
B.MongoDB uses a global schema that applies to all collections within a database.
C.MongoDB collections are schema-less, meaning documents in the same collection do not need to have the same set of fields or structure.
D.Every document in a collection must strictly adhere to the same schema, enforced by the database.
Correct Answer: MongoDB collections are schema-less, meaning documents in the same collection do not need to have the same set of fields or structure.
Explanation:
A core feature of MongoDB is its flexible schema model. Unlike relational databases, collections do not enforce a rigid document structure by default. This allows for evolving application requirements without complex database migrations. While you can enforce a schema at the application level (using Mongoose) or at the database level (using JSON Schema validation), the default behavior is schema-less.
Incorrect! Try again.
40You have a collection of events with an eventDate field stored as an ISODate. Which query finds all events that occurred on or after the beginning of 2023 and before the beginning of 2024?
To query a date range, you should use the comparison operators lt (less than). This query correctly selects all documents where eventDate is on or after the first moment of 2023-01-01 and strictly before the first moment of 2024-01-01, effectively capturing all events within the year 2023.
Incorrect! Try again.
41Consider a users collection with a document for Alice: { "_id": 1, "name": "Alice", "profile": { "tags": ["A", "B"], "score": 10 } }. What is the final state of Alice's document after executing the following command?
The updateMany command targets all documents where profile.tags contains 'B', which includes Alice's document. The update operator has two parts:
$inc: { 'profile.score': 5 } increments the score from 10 to 15.
$addToSet: { 'profile.tags': 'D' } adds 'D' to the tags array only if it doesn't already exist. Since 'D' is not present, the array becomes ["A", "B", "D"].
Both operations are applied atomically to the document.
Incorrect! Try again.
42Given a products collection where a document has a variants array like: { name: 'Shirt', variants: [ { color: 'red', stock: 10 }, { color: 'blue', stock: 5 }, { color: 'red', stock: 0 } ] }
What is the precise output of the following query?
This query demonstrates the interaction between the positional projection operator.
The gt: 0 }).
The variants.$ in the projection operator then returns only the first element of the variants array that matched the query condition. In this case, it's the { color: 'red', stock: 10 } element.
Incorrect! Try again.
43You execute an insertMany operation on an empty collection with the ordered: false option, where one of the documents violates the unique _id constraint. What is the outcome?
A.The operation fails completely before inserting any documents, and the collection remains empty.
B.The operation is aborted when the duplicate key is found. Only the document { _id: 1, val: 'A' } is inserted.
C.The operation continues after the error. The documents { _id: 1, val: 'A' } and { _id: 2, val: 'B' } are inserted. A write error is reported for the third document.
D.The behavior is undefined and depends on the storage engine.
Correct Answer: The operation continues after the error. The documents { _id: 1, val: 'A' } and { _id: 2, val: 'B' } are inserted. A write error is reported for the third document.
Explanation:
The ordered: false option tells MongoDB to attempt to insert all documents in the array, even if one or more of them fail. The server will not stop processing the batch on the first error. In this case, it will successfully insert { _id: 1, val: 'A' } and { _id: 2, val: 'B' }. When it attempts to insert { _id: 1, val: 'C' }, it will fail with a duplicate key error. The operation result will contain information about the successful inserts and the write error.
Incorrect! Try again.
44Analyze the following Mongoose schema and subsequent code. After user.save() is successfully executed, what will be the values of user.level, user.xp, and the virtual property user.rank?
A.The result variable will be { _id: ..., name: 'Gadget', stock: 1 }, and a new document will be inserted.
B.The operation will throw a ValidationError because stock is not defined in the schema with a default value.
C.The result variable will be null, and a document { name: 'Gadget' } will be inserted, with stock remaining unset.
D.The result variable will be null, and a new document { name: 'Gadget', stock: 1 } will be inserted into the database.
Correct Answer: The result variable will be null, and a new document { name: 'Gadget', stock: 1 } will be inserted into the database.
Explanation:
This question tests the interaction of several findOneAndUpdate options:
upsert: true: Since no document matches { name: 'Gadget' }, MongoDB will create a new one.
Document Creation: During an upsert, the new document is created by applying the update operation ($inc: { stock: 1 }) to a document based on the query filter ({ name: 'Gadget' }). This results in a new document { name: 'Gadget', stock: 1 } being inserted.
new: false: This option specifies that the function should return the document as it was before the update. Since the document did not exist before, the return value (result) is null.
Incorrect! Try again.
46When implementing cursor-based pagination on a posts collection sorted by createdAt: -1, you notice multiple posts can have the exact same createdAt timestamp. A common solution is to add _id: -1 as a secondary sort field. How must the query filter be structured to correctly fetch the next page, given the last post seen had lastCreatedAt and lastId?
Using a simple $lt on both fields is incorrect. The correct logic requires handling two cases:
Documents with a createdAt timestamp that is strictly less (older) than the last one seen.
Documents that have the exact samecreatedAt timestamp as the last one, in which case we use the unique _id field as a tie-breaker to find the next ones in the sequence.
The $or operator correctly combines these two conditions, ensuring no documents are skipped or repeated, thus providing stable and correct pagination even with duplicate sort key values.
Incorrect! Try again.
47What is a key characteristic of a Capped Collection in MongoDB that differentiates it from a standard collection, and what is its primary use case?
MongoDB Terminology - database, collection, document and files
Hard
A.They support transactions and are used for financial data.
B.They enforce a strict schema on all documents inserted, used for data validation at the database level.
C.They automatically shard data across multiple servers for horizontal scaling.
D.They are fixed-size collections that maintain insertion order and overwrite the oldest entries when full, ideal for logging or caching.
Correct Answer: They are fixed-size collections that maintain insertion order and overwrite the oldest entries when full, ideal for logging or caching.
Explanation:
Capped collections are a special type of collection with a fixed maximum size and, optionally, a maximum number of documents. Once a collection is full, the oldest documents are overwritten by new ones, behaving like a circular buffer. They preserve insertion order, which makes them highly performant for writes and for reading the most recently inserted items (e.g., tailable cursors). This makes them perfect for high-throughput logging, caching, or storing real-time event data where only the most recent information is relevant.
Incorrect! Try again.
48You have a Mongoose model with a static method and an instance method. Given const alice = await User.findOne({ name: 'Alice' });, which statement correctly describes the valid and invalid use of these methods?
A.Only User.findByName('Alice') is a valid call; alice.hasName('Alice') is invalid.
B.Both User.findByName('Alice') and alice.hasName('Alice') are valid calls.
C.Both User.hasName('Alice') and alice.findByName('Alice') are valid calls.
D.Only alice.hasName('Alice') is a valid call; User.findByName('Alice') is invalid.
Correct Answer: Both User.findByName('Alice') and alice.hasName('Alice') are valid calls.
Explanation:
This question tests the fundamental difference between static and instance methods in Mongoose.
Static methods (defined on schema.statics) are called on the Model itself (e.g., User). User.findByName('Alice') is the correct way to use it.
Instance methods (defined on schema.methods) are called on a document instance (e.g., alice). alice.hasName('Alice') is the correct way to use it, where this inside the method refers to the alice document.
Therefore, both of the specified calls are syntactically correct and follow the intended design pattern.
Incorrect! Try again.
49By default, Mongoose does not run schema validators on updateOne and updateMany operations. An update operation is performed on a document that would violate a schema validator if it were run. What is the outcome?
A.The update partially succeeds, adding the tag but marking the document as invalid.
B.The update fails with a ValidationError because Mongoose automatically enables validation for all update operations.
C.The update succeeds, and the tags array becomes ['news', 'announcements'] because validators are not run by default.
D.The update succeeds, but the invalid tag 'announcements' is silently ignored and not added to the array.
Correct Answer: The update succeeds, and the tags array becomes ['news', 'announcements'] because validators are not run by default.
Explanation:
A critical concept in Mongoose is that query middleware for operations like updateOne, updateMany, and findOneAndUpdate does not run schema validators by default. These commands are passed directly to the MongoDB driver. To enable validation, you must explicitly add the runValidators: true option to the query. Since it is absent here, the operation succeeds, and the data that violates the schema rule (maxlength: 8) is inserted into the database.
Incorrect! Try again.
50To optimize the query db.users.find({ status: "active" }).sort({ lastLogin: -1 }) for a large collection, which compound index provides the best performance according to the Equality-Sort-Range (ESR) rule?
data manipulation - find
Hard
A.{ "status": 1, "lastLogin": -1 }
B.A text index on both status and lastLogin.
C.Two separate single-field indexes: one on status and one on lastLogin.
D.{ "lastLogin": -1, "status": 1 }
Correct Answer: { "status": 1, "lastLogin": -1 }
Explanation:
The ESR (Equality, Sort, Range) rule is a guideline for ordering fields in a compound index. The optimal order is:
Equality: Fields on which you perform an exact match (status: "active").
Sort: Fields on which you sort the results (lastLogin: -1).
Range: Fields on which you perform range queries (lt).
Following this rule, the index { "status": 1, "lastLogin": -1 } is optimal because MongoDB can first quickly filter the documents by the status field and then traverse the index in the pre-sorted order of lastLogin to get the results, avoiding an expensive in-memory sort.
Incorrect! Try again.
51You execute use newDB in the mongo shell, followed by db.createCollection("myColl"). Immediately after, you execute db.dropDatabase(). At what point are the physical database files for newDB actually created on disk, and what is the final result?
MongoDB shell commands - create database, create documents, create collections, drop collection, drop database
Hard
A.Files are created on use newDB. The dropDatabase() call then removes them.
B.Files are created on use newDB. The dropDatabase() call fails because the database is empty.
C.Files are not created until the first document is inserted. The dropDatabase() call does nothing.
D.Files are created on db.createCollection("myColl"). The dropDatabase() call then removes them.
Correct Answer: Files are created on db.createCollection("myColl"). The dropDatabase() call then removes them.
Explanation:
MongoDB creates databases lazily. The use newDB command only switches the shell's internal db context pointer. The database itself, along with its physical files, is not created until the first write operation occurs. A createCollection command is considered a write operation. Therefore, the files are created at that point. The subsequent db.dropDatabase() command, which operates on the current db context (newDB), then successfully removes the newly created database and its files.
Incorrect! Try again.
52In a MongoDB replica set, what level of atomicity is guaranteed for the following single updateOne operation?
A.Field-level atomicity. push is atomic, but not together.
B.Transaction-level atomicity. It requires an explicit transaction to be atomic.
C.Document-level atomicity. Both modifications (push) are applied to the single document as a single, indivisible operation.
D.None. The push operations are independent and may succeed or fail separately.
Correct Answer: Document-level atomicity. Both modifications (push) are applied to the single document as a single, indivisible operation.
Explanation:
MongoDB guarantees atomicity for all write operations that affect a single document. Even if the operation includes multiple update operators modifying different fields (like push here), MongoDB ensures that either all modifications are applied to the document, or none are. This single-document atomicity is a core feature and does not require an explicit multi-document transaction.
Incorrect! Try again.
53A developer defines a Mongoose schema where a field is type Number but provides a string value when creating a new document instance. What is Mongoose's behavior during the save() operation?
javascript
const itemSchema = new mongoose.Schema({ price: Number });
const Item = mongoose.model('Item', itemSchema);
const newItem = new Item({ price: '19.99' });
await newItem.save();
Introduction to Mongoose
Hard
A.It saves the document, but the price field is stored as the string '19.99' in the database.
B.It successfully saves the document by automatically casting the string '19.99' to the number 19.99.
C.It saves the document, but the price field is set to null due to the failed cast.
D.It throws a CastError because the type of '19.99' is a string, not a number.
Correct Answer: It successfully saves the document by automatically casting the string '19.99' to the number 19.99.
Explanation:
One of the key features of Mongoose is its built-in type casting. When you provide data to create or update a document, Mongoose attempts to cast the values to match the types defined in the schema. In this case, the string '19.99' can be successfully parsed and converted into a Number. This cast happens before validation and saving, so the document is stored in the database with price as a numeric type.
Incorrect! Try again.
54Which Mongoose query correctly performs a nested population, retrieving an Order document while also populating the user's name and, for each item in the items array, the product's name and price?
Mongoose's populate method is powerful enough to handle this scenario. To populate a path that is nested inside an array of subdocuments, you use dot notation for the path string. The path 'items.productId' tells Mongoose to go into the items array and, for each object in the array, populate the productId field. You can chain multiple populate calls or pass an array of population options to populate multiple paths like user and items.productId in the same query.
Incorrect! Try again.
55In a 3-node replica set (Primary, Secondary, Secondary), a write operation is issued with a write concern of w: "majority". At that moment, one of the secondary nodes is down. What is the expected outcome of the write operation?
MongoDB database installation and shell installation
Hard
A.The write will succeed after being acknowledged by the Primary and the single remaining Secondary.
B.The write will fail immediately, returning an error to the client that a majority is not available.
C.The write will hang indefinitely until the downed secondary comes back online.
D.The write will succeed after being acknowledged by the Primary only, as majority is ignored when nodes are down.
Correct Answer: The write will succeed after being acknowledged by the Primary and the single remaining Secondary.
Explanation:
A "majority" in a replica set refers to a majority of the voting members. In a standard 3-node replica set, all nodes are voting members, so a majority is ceil(3 / 2) = 2. Since the Primary and one Secondary are still up and can communicate, a majority of 2 is available. The write operation will be sent to the Primary, replicated to the available Secondary, and once both have acknowledged the write to their respective oplogs, the w: "majority" condition is met, and a success response is returned to the client.
Incorrect! Try again.
56A developer uses the mongoose-autopopulate plugin on a createdBy field in a Post schema. What is the most significant and common performance pitfall of this approach when applied universally?
Models
Hard
A.It adds an extra database query to fetch the User document every time a Post is queried, even when the createdBy data is not needed for that specific operation.
B.It breaks queries that try to sort by the createdBy field.
C.It causes the Mongoose schema validation to be bypassed for the createdBy field.
D.It makes it impossible to use the .lean() method to get plain JavaScript objects.
Correct Answer: It adds an extra database query to fetch the User document every time a Post is queried, even when the createdBy data is not needed for that specific operation.
Explanation:
The main downside of automatic population is its indiscriminate nature. While convenient, it means that every single find, findOne, etc., query on the Post model will trigger a second query to the User collection to perform the population. In many cases (e.g., fetching a list of post titles for a sitemap), the populated user data is unnecessary. This leads to redundant database load and increased latency, a classic performance pitfall of implicit, 'magic' behavior.
Incorrect! Try again.
57In a large, sharded MongoDB cluster, what is the primary and most severe performance consequence of executing a deleteMany command where the query filter does not include the shard key?
data manipulation - delete
Hard
A.The operation will fail with an error because the shard key is required for all delete operations.
B.The operation will only run on the primary shard, leading to incomplete data deletion.
C.MongoDB will perform a full collection scan on a single shard to find the shard key, then target the correct shard.
D.The mongos query router will broadcast the delete command to every shard in the cluster (a scatter-gather operation), potentially causing a cluster-wide performance degradation.
Correct Answer: The mongos query router will broadcast the delete command to every shard in the cluster (a scatter-gather operation), potentially causing a cluster-wide performance degradation.
Explanation:
When a query in a sharded environment does not include the shard key, the mongos router cannot determine which shard(s) hold the relevant data. As a result, it must broadcast the query to all shards. This is known as a scatter-gather query. For a deleteMany operation, this means every shard must execute the query, which can lead to high CPU, I/O, and network load across the entire cluster, significantly impacting overall performance, especially if the operation is frequent or targets many documents.
Incorrect! Try again.
58A MongoDB document is limited to 16 megabytes in size. An application needs to store user-uploaded files that are often larger than this limit (e.g., 100MB videos). What is the canonical MongoDB solution for handling this requirement?
Getting familiar with MongoDB documents and collections
Hard
A.Store the file's binary data in a BSON BinData field and enable collection-level compression.
B.Manually split the file into an array of 15MB chunks within a single document.
C.Store the files on a traditional file system and only store the file path string in the MongoDB document.
D.Use GridFS, a specification for storing and retrieving large files by chunking them into separate documents within special collections (fs.files and fs.chunks).
Correct Answer: Use GridFS, a specification for storing and retrieving large files by chunking them into separate documents within special collections (fs.files and fs.chunks).
Explanation:
GridFS is the official, built-in solution for this exact problem. It provides a driver-level API that abstracts the process of splitting a large file into smaller chunks (typically 255KB each) and storing them as individual documents in a chunks collection. A separate metadata document is stored in a files collection, containing information like the filename, content type, and the sequence of chunk IDs. This approach overcomes the 16MB document limit and is well-integrated into the MongoDB ecosystem for managing large files.
Incorrect! Try again.
59In a MongoDB replica set, a client can specify a Read Concern to control the consistency of data it reads. Which Read Concern level ensures that a query reads data from a snapshot of the data that has been acknowledged by a majority of the replica set members, thus preventing reads of rolled-back data?
Introduction to MongoDB
Hard
A.available
B.local
C.snapshot
D.majority
Correct Answer: majority
Explanation:
The majority read concern provides a crucial consistency guarantee. It ensures that the data being read has been written to the oplogs of a majority of the replica set's voting nodes. This means the data is durable and will not be rolled back in the event of a primary failover. Reading with local or available can be faster but risks reading data that might be rolled back if the primary fails before the data is replicated to a majority.
Incorrect! Try again.
60What is a key difference between db.collection.deleteMany({}) and db.collection.drop() in MongoDB?
MongoDB shell commands - drop collection, drop database
Hard
A.There is no functional difference; drop() is just an alias for deleteMany({}).
B.drop() removes the collection and all its indexes, while deleteMany({}) only removes the documents, leaving the empty collection and its indexes intact.
C.deleteMany({}) can be rolled back in a transaction, but drop() cannot.
D.deleteMany({}) is faster because it does not have to remove indexes.
Correct Answer: drop() removes the collection and all its indexes, while deleteMany({}) only removes the documents, leaving the empty collection and its indexes intact.
Explanation:
This distinction is critical for database management. deleteMany({}) is a data manipulation (DML) operation that iterates through and removes every document, which can be slow and resource-intensive for large collections. It leaves the collection's structure, including all its indexes, in place. In contrast, db.collection.drop() is a metadata (DDL) operation. It is extremely fast because it removes the entire collection namespace and all associated index files at a low level, rather than deleting documents one by one.