Unit 2: MongoDB Basics and CRUD Operations - Subjective Questions
CSE494 — Intelligent Nosql Databases • Practice Questions with Detailed Answers
20 questions
Define MongoDB and explain its major characteristics as a NoSQL database.
MongoDB is a document-oriented NoSQL database management system that stores data in flexible, JSON-like documents using BSON.
- It stores records as documents instead of rows.
- Documents are grouped into collections instead of tables.
- It supports flexible schemas, so documents in the same collection may have different fields.
- It provides horizontal scalability through sharding.
- It supports replication for high availability and fault tolerance.
- It provides CRUD operations, indexing, aggregation, and transactions.
- Its document model is suitable for semi-structured and rapidly changing data.
MongoDB is commonly used for content management, real-time applications, catalogs, social applications, and big-data systems.
Explain the concepts of databases, collections, and documents in MongoDB with a suitable example.
MongoDB organizes data using a hierarchical document model:
- A database is a logical container that holds collections.
- A collection is a group of related documents and is conceptually similar to a table in a relational database.
- A document is an individual record stored in BSON format and is conceptually similar to a row.
Example:
use university
db.students.insertOne({
name: "Asha",
rollNo: 101,
department: "Computer Science"
})Here, university is the database, students is the collection, and the object containing name, rollNo, and department is a document. Unlike relational rows, MongoDB documents can contain nested objects and arrays.
What is a MongoDB document? Describe its structure and explain the role of the _id field.
A MongoDB document is a set of field-value pairs stored internally in BSON format. It resembles a JSON object but supports additional data types.
Example:
{
_id: ObjectId("64a000000000000000000001"),
name: "Ravi",
age: 21,
skills: ["MongoDB", "JavaScript"],
address: {
city: "Pune",
country: "India"
}
}The _id field:
- Uniquely identifies each document within a collection.
- Is automatically generated when it is not supplied by the user.
- Usually contains an
ObjectIdvalue. - Is automatically indexed by MongoDB.
- Helps MongoDB locate, update, and delete individual documents efficiently.
A document may contain primitive values, arrays, embedded documents, and other BSON-supported types.
Explain BSON and compare it with JSON. Why does MongoDB use BSON internally?
BSON, or Binary JSON, is a binary representation of JSON-like documents used internally by MongoDB.
Comparison between BSON and JSON:
- JSON is a text-based format, whereas BSON is binary.
- JSON supports a limited set of data types, whereas BSON supports types such as
ObjectId,Date,Decimal128,Binary, andTimestamp. - BSON stores length information, which allows MongoDB to scan and process documents efficiently.
- JSON is generally more readable to humans.
- BSON may require more storage than plain JSON for some data.
MongoDB uses BSON because it supports richer data types, efficient traversal, serialization, and deserialization. BSON also allows MongoDB to represent dates, binary data, and unique identifiers more accurately than standard JSON.
Describe the important BSON data types supported by MongoDB and give examples of their use.
MongoDB supports several BSON data types, including:
- String: Stores textual data, such as
"name": "Meera". - Double: Stores floating-point numbers.
- Int32 and Int64: Store 32-bit and 64-bit integer values.
- Boolean: Stores
trueorfalsevalues. - Array: Stores an ordered list of values, such as
"tags": ["db", "nosql"]. - Embedded document: Stores a document inside another document.
- ObjectId: Provides a unique identifier for documents.
- Date: Stores date and time values.
- Null: Represents an empty or missing value.
- Regular expression: Supports pattern matching.
- Binary data: Stores files or other binary content.
- Decimal128: Stores high-precision decimal values, useful for financial data.
Choosing an appropriate BSON type improves data accuracy, query behavior, sorting, and indexing.
Explain how to create and switch to a database in MongoDB. What happens if the database does not yet exist?
MongoDB uses the use command to switch to a database or select a database name.
use companyDBIf companyDB already exists, MongoDB switches the current session to that database. If it does not exist, MongoDB creates a database context with that name, but the database is not physically created immediately.
The database becomes visible after data or another database object is stored in it. For example:
use companyDB
db.employees.insertOne({
name: "Neha",
department: "IT"
})The insertOne() operation creates the employees collection automatically if it does not already exist, and the database becomes persistent because it now contains data.
Describe the methods for creating collections in MongoDB. Distinguish between implicit and explicit collection creation.
MongoDB supports both implicit and explicit collection creation.
Implicit creation:
A collection is created automatically when data is first inserted into it.
db.products.insertOne({
name: "Keyboard",
price: 1200
})Explicit creation:
A collection can be created using createCollection() when specific options are required.
db.createCollection("logs", {
capped: true,
size: 100000
})Difference:
- Implicit creation is simple and requires no configuration.
- Explicit creation allows options such as capped collection size, validation rules, and other collection settings.
- Explicit creation is preferred when the collection requires controlled structure or special behavior.
The command show collections can be used to list collections in the current database.
Explain how to drop a collection and a database in MongoDB. Discuss the precautions that should be taken before performing these operations.
A collection can be removed using the drop() method:
db.products.drop()The current database can be removed using:
db.dropDatabase()Important precautions include:
- These operations permanently remove data and cannot normally be undone.
- The current database or collection should be verified before execution.
- A backup should be created when the data may be needed later.
- User permissions should be checked to prevent unauthorized deletion.
- Production operations should be tested in a staging environment first.
- Applications depending on the collection should be stopped or updated.
- The result of the operation should be checked to confirm whether it succeeded.
Dropping a database is more destructive than dropping an individual collection because it removes all collections and data in that database.
Explain the CRUD operations in MongoDB with representative commands.
CRUD stands for Create, Read, Update, and Delete.
- Create: Inserts documents into a collection.
db.students.insertOne({ name: "Asha", marks: 85 })- Read: Retrieves documents using
find()orfindOne().
db.students.find({ marks: { $gte: 50 } })- Update: Modifies existing documents using update operators.
db.students.updateOne(
{ name: "Asha" },
{ $set: { marks: 90 } }
)- Delete: Removes documents using
deleteOne()ordeleteMany().
db.students.deleteOne({ name: "Asha" })MongoDB also provides insertMany(), updateMany(), projections, sorting, pagination, and upsert functionality for more advanced CRUD tasks.
Differentiate between insertOne() and insertMany() in MongoDB. Explain the advantages of bulk insertion.
insertOne() adds a single document, while insertMany() adds multiple documents in one operation.
db.users.insertOne({ name: "Kiran", age: 22 })db.users.insertMany([
{ name: "Kiran", age: 22 },
{ name: "Lata", age: 24 }
])Advantages of insertMany() include:
- Fewer network round trips between the client and server.
- Better performance when importing or loading large data sets.
- A convenient way to submit a group of related documents.
- Support for ordered and unordered insertion behavior.
In ordered insertion, MongoDB stops processing after an error by default. With { ordered: false }, MongoDB can continue inserting other valid documents even if one document fails.
Explain MongoDB query operators and update operators with suitable examples.
MongoDB operators specify conditions or modifications in database operations.
Query operators:
$gt,$gte,$lt, and$ltecompare values.$eqchecks equality.$inmatches any value from a list.$and,$or, and$notcombine conditions.$existschecks whether a field is present.
Example:
db.products.find({
price: { $gte: 500, $lte: 2000 },
category: { $in: ["books", "electronics"] }
})Update operators:
$setassigns a value.$unsetremoves a field.$incincrements a numeric field.$pushadds an item to an array.$pullremoves matching array items.
Example:
db.products.updateOne(
{ name: "Book" },
{ $inc: { stock: 5 }, $set: { available: true } }
)Compare embedded documents and references in MongoDB data modeling. State the situations in which each approach is appropriate.
MongoDB supports two major ways to represent relationships.
Embedded documents:
Related data is stored inside the parent document.
{
name: "Asha",
address: {
city: "Delhi",
postalCode: "110001"
}
}Embedding is appropriate when:
- Related data is usually accessed together.
- The embedded data is small and bounded.
- The relationship is one-to-one or one-to-few.
- Atomic updates to the parent and child data are useful.
References:
A document stores the identifier of another document.
{
orderNo: 1001,
customerId: ObjectId("64a000000000000000000001")
}Referencing is appropriate when:
- Related data is large or unbounded.
- Data is shared by many documents.
- Child data is accessed independently.
- Frequent updates would otherwise require changing many embedded documents.
The choice should be based on access patterns, update frequency, document size, and relationship complexity.
Describe the principles of data modeling in MongoDB and explain why application access patterns are important.
MongoDB data modeling should be designed around how the application reads and modifies data.
Important principles include:
- Store data that is commonly accessed together in the same document.
- Embed related data when the relationship is small and bounded.
- Use references when data is large, shared, or independently managed.
- Avoid unbounded arrays because documents may grow excessively.
- Keep frequently updated data separate when embedding would cause large rewrites.
- Design fields and document structure for common query patterns.
- Consider the maximum BSON document size when modeling large records.
- Use indexes to support important queries.
- Maintain consistency and avoid unnecessary duplication unless denormalization improves performance.
Unlike traditional normalization-first design, MongoDB often uses controlled denormalization to reduce joins and improve read performance. Therefore, understanding the application's read and write patterns is essential before deciding how documents should be structured.
Explain normalization and denormalization in MongoDB. Compare their benefits and limitations.
Normalization stores related information in separate collections and connects it using references.
Benefits of normalization:
- Reduces duplication.
- Makes updates to shared data easier.
- Helps maintain a single authoritative copy of data.
Limitations of normalization:
- May require multiple queries or
$lookupoperations. - Can increase application complexity.
- May reduce read performance for frequently joined data.
Denormalization stores related data together, often by embedding or duplicating selected fields.
Benefits of denormalization:
- Reduces the number of queries.
- Improves read performance for common access patterns.
- Makes related data available in one document.
Limitations of denormalization:
- Duplicated values must be updated consistently.
- Documents may become larger.
- Write operations can become more expensive.
MongoDB applications commonly use a balanced approach in which frequently read data is embedded and independently managed data is referenced.
What is an index in MongoDB? Explain how indexes improve query performance and describe their costs.
An index is a special data structure that stores selected field values in an ordered form, allowing MongoDB to locate matching documents without scanning the entire collection.
Example:
db.students.createIndex({ rollNo: 1 })Here, 1 specifies ascending order.
Indexes improve performance by:
- Reducing the number of documents examined.
- Supporting fast equality, range, sorting, and prefix queries.
- Allowing MongoDB to use an index scan instead of a collection scan.
- Improving the response time of frequently executed queries.
Indexes also have costs:
- They consume additional disk and memory.
- Insert, update, and delete operations must maintain index entries.
- Too many indexes may reduce write performance.
- Poorly selected indexes may provide little benefit.
Indexes should be created based on actual query patterns and verified with execution plans.
Explain the different types of indexes commonly used in MongoDB.
MongoDB provides several types of indexes:
- Single-field index: Indexes one field, such as
{ age: 1 }. - Compound index: Indexes multiple fields, such as
{ department: 1, salary: -1 }. - Multikey index: Automatically supports array fields.
- Unique index: Prevents duplicate values for the indexed field.
- Text index: Supports text search in string fields.
- Geospatial index: Supports location-based queries.
- Hashed index: Stores hashed field values and is useful for certain distribution patterns.
- TTL index: Automatically removes documents after a specified time period.
- Sparse index: Includes only documents that contain the indexed field.
- Partial index: Includes only documents satisfying a specified filter.
The appropriate type depends on the data type, query conditions, uniqueness requirements, expiration rules, and application access patterns.
Explain compound indexes in MongoDB and discuss the importance of field order in a compound index.
A compound index contains multiple fields in a defined order.
db.orders.createIndex({ customerId: 1, orderDate: -1 })This index first sorts by customerId in ascending order and then by orderDate in descending order for each customer.
Field order is important because:
- MongoDB can efficiently use the index for queries on the first field.
- It can use the index for the prefix
{ customerId: 1 }. - It may not efficiently use the index for a query that only filters by
orderDate. - Equality fields are often placed before range fields.
- Fields used for sorting should be arranged to support the required sort order.
The design of a compound index should reflect the most common combinations of filtering, sorting, and range conditions. An index should be tested with explain() rather than selected only by intuition.
What is query optimization in MongoDB? Explain how the explain() method helps analyze a query.
Query optimization is the process of improving query execution so that it uses fewer resources and returns results faster.
MongoDB provides the explain() method to inspect a query plan.
db.students.find({ department: "IT" }).explain("executionStats")Important information in the result includes:
- The selected query plan.
- Whether MongoDB used an index scan or a collection scan.
- The number of documents examined.
- The number of documents returned.
- The number of index keys examined.
- Estimated or actual execution time.
A query is generally more efficient when it examines a small number of documents and index keys compared with the total collection size. Query optimization may involve creating a suitable index, returning only required fields, limiting results, improving data modeling, and avoiding unnecessary operations.
Explain projection, sorting, limiting, and skipping in MongoDB queries with examples.
MongoDB provides cursor methods to control query output.
Projection selects fields to include or exclude:
db.students.find(
{ department: "IT" },
{ name: 1, marks: 1, _id: 0 }
)Sorting orders the result. The values 1 and -1 represent ascending and descending order:
db.students.find().sort({ marks: -1 })Limiting restricts the number of returned documents:
db.students.find().limit(10)Skipping ignores a specified number of documents and is often used with pagination:
db.students.find().skip(20).limit(10)These operations improve usability and may reduce the amount of data transferred to the application. Appropriate indexes should be used to support filtering and sorting efficiently.
Explain upsert operations in MongoDB. How does an upsert differ from a normal update?
An upsert combines update and insert behavior. If a matching document exists, MongoDB updates it. If no matching document exists, MongoDB inserts a new document based on the filter and update data.
Example:
db.inventory.updateOne(
{ itemCode: "A101" },
{ $set: { item: "Pen", quantity: 50 } },
{ upsert: true }
)Difference from a normal update:
- A normal update modifies matching documents and does nothing if no document matches, unless another option is used.
- An upsert creates a new document when there is no match.
- Upserts are useful for synchronization, configuration records, counters, and idempotent data loading.
- The filter should be carefully designed to avoid creating unintended duplicate or incomplete documents.
A unique index may be required when the matching field must remain unique.
Define MongoDB and explain its major characteristics as a NoSQL database.
MongoDB is a document-oriented NoSQL database management system that stores data in flexible, JSON-like documents using BSON.
- It stores records as documents instead of rows.
- Documents are grouped into collections instead of tables.
- It supports flexible schemas, so documents in the same collection may have different fields.
- It provides horizontal scalability through sharding.
- It supports replication for high availability and fault tolerance.
- It provides CRUD operations, indexing, aggregation, and transactions.
- Its document model is suitable for semi-structured and rapidly changing data.
MongoDB is commonly used for content management, real-time applications, catalogs, social applications, and big-data systems.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →