Interview Question And Answer - MongoDB

Interview Question And Answer Content - MongoDB

Beginner - Level

Answer:-  MongoDB is a NoSQL, document-oriented database that stores data in BSON format (Binary JSON).

Answer:-   MongoDB is a NoSQL document-oriented database, meaning it stores data as JSON-like documents instead of tables and rows.

Answer:-

  • Schema-less (flexible data models)
  • High scalability and performance
  • Replication and high availability
  • Indexing for fast queries
  • Aggregation framework

Answer:-   BSON (Binary JSON) is MongoDB’s binary-encoded JSON format used for storing documents efficiently.

Answer:-  A collection is a group of related documents, similar to a table in relational databases.

Answer:-  A document is a JSON-like object that stores data as key-value pairs.

Answer:-

  • MongoDB is schema-less, MySQL has a rigid schema.
  • MongoDB stores data as documents, MySQL uses tables and rows.
  • MongoDB scales horizontally, MySQL scales vertically.

Answer:-Run the command:  mongod

Answer:-  mongod –version

Answer: db.collection.insertOne({“name”: “Alice”, “age”: 25}

Answer: db.collection.insertMany([{“name”: “Bob”}, {“name”: “Charlie”}])

Answer: db.collection.find({“age”: 25})

Answer: db.collection.updateOne({“name”: “Alice”}, {“$set”: {“age”: 26}})

Answer: db.collection.updateMany({}, {“$set”: {“status”: “active”}})

Answer: db.collection.deleteOne({“name”: “Alice”})

Answer: db.collection.deleteMany({“age”: {“$lt”: 18}})

Answer: db.collection.drop()

Answer: db.dropDatabase()

Answer:An index improves query performance by speeding up data retrieval

Answer:db.collection.createIndex({name: 1})

Answer:db.collection.getIndexes()

Answer:db.collection.dropIndex({name: 1})

Answer: A compound index is an index on multiple fields, e.g., db.collection.createIndex({name: 1, age: -1})

Answer: A powerful tool for data analysis and transformation in MongoDB

Answer: db.collection.aggregate([ { “$match”: { “age”: { “$gt”: 20 } } } ])

Answer: It groups documents and applies aggregation operations like sum, avg, etc

Answer: It sorts documents, e.g., db.collection.aggregate([ { “$sort”: { “age”: -1 } } ])

Answer:  It limits the number of returned documents, e.g., db.collection.aggregate([ { “$limit”: 5 } ])

Answer: Using embedded documents (denormalization) or references (normalization)

Answer: Storing related data inside a single document

Answer: Storing related data separately and linking using ObjectIds

Answer: A process to ensure data availability by maintaining multiple copies of data

Answer:A group of MongoDB servers that maintain copies of the same data.

Answer: Embedding is better for one-to-few relationships, referencing for one-to-many.

Answer: A method to distribute large datasets across multiple servers.

Answer: The node that handles write operations.

Answer:  A node that replicates data from the primary node

Answer: Start MongoDB with –auth and create users.

Answer: db.createUser({user: “admin”, pwd: “password”, roles: [“readWrite”]})

Answer:  Roles define permissions, e.g., “read”, “readWrite”, “dbAdmin”, etc.

Answer: Use: mongodump –db mydb –out /backup/path

Answer:  Use: mongorestore /backup/path

Answer:  A system for storing large files, such as images and videos.

Intermediate - Level

Answer:- MongoDB is a NoSQL database with flexible schemas, while MySQL is a relational database using
structured tables

Answer:- Scalability, flexible schema, high availability, and horizontal scaling through sharding.

Answer:-  A fixed-size collection that automatically overwrites oldest documents when it reaches the limit.

Answer:-  db.createCollection(‘log’, {capped: true, size: 100000})

Answer:-  An ObjectId in MongoDB is 12 bytes long.

Answer:-  db.collection.find({ fieldName: { $exists: true } })

Answer:- To perform pattern matching on string fields.

Answer:-  Use the dot notation: db.collection.updateOne({ ‘user.name’: ‘Alice’ }, { $set: { ‘user.age’: 30 } })

Answer:- find() returns multiple documents, while findOne() returns a single document.

Answer:-Matches documents where an array field contains all specified values.

Answer:- Use the $regex operator with ‘i’ option: db.collection.find({ name: { $regex: ‘john’, $options: ‘i’ } })

Answer:  It matches documents containing an array field with elements that meet multiple criteria.

Answer:  db.collection.updateMany({}, { $rename: { ‘oldField’: ‘newField’ } })

Answer: $push adds an element to an array, while $addToSet adds only if it doesn’t already exist.

Answer: db.collection.updateOne({}, { $pull: { arrayField: value } })

Answer:  db.collection.countDocuments()

Answer: db.getCollectionNames().includes(‘collectionName’)

Answer:A document left behind after a shard migration in sharded clusters.

Answer:  An index on multiple fields; useful when queries filter or sort by multiple fields.

Answer: db.collection.createIndex({ email: 1 }, { unique: true })

Answer: $group groups documents, while $project reshapes documents by including/excluding fields.

Answer: It uniquely identifies a document; automatically indexed.

Answer: Using the $lookup aggregation stage.

Answer: db.collection.updateOne({}, { $inc: { count: 1 } })

Answer: db.collection.distinct(‘fieldName’)

Answer:  Provides execution details of a query to optimize performance.

Answer:  A query that can be satisfied using only an index without reading documents.

Answer: db.collection.createIndex({ name: ‘text’ })

Answer: db.collection.find({ $text: { $search: ‘keyword’ } })

Answer:  Allows multiple aggregation pipelines to run in a single query.

Answer:  A cloud database service for managing MongoDB clusters.

Answer: A feature that allows real-time monitoring of changes in a collection.

Answer:  db.collection.watch()

Answer: A way to ensure atomicity across multiple documents using transactions.

Answer: session.startTransaction()

Answer:  session.abortTransaction()

Answer: Storing large files, such as images and videos, in MongoDB.

Answer: db.collection.find().sort({ field: -1 }).limit(1)

Answer:A special collection that records all changes in a replica set.

Answer: It is the default MongoDB storage engine, providing better performance and concurrency.

Answer: Enable profiling with db.setProfilingLevel(1) and check system.profile collection.

Answer: Use the –enableEncryption option when starting MongoDB

Answer: Allows encryption of specific fields without encrypting the entire database.

Answer:  Create users with specific roles using db.createUser().

Answer: Enable sharding with sh.enableSharding(‘databaseName’) and shard a collection with
sh.shardCollection().

Answer: A router that directs client requests to the appropriate shard in a sharded cluster.

Answer: db.serverStatus().connections

Answer: rs.printSlaveReplicationInfo()

Answer:An election process selects a new primary node.

Advance - Level

Answer:- Replica sets provide redundancy and high availability, while sharding distributes data across
multiple servers for scalability.

Answer:- Through read and write concerns, journaling, and replication

Answer:- Majority waits for acknowledgment from most replica set members, while Local acknowledges after
writing to the primary node.

Answer:-  Using multi-document ACID transactions introduced in MongoDB 4.2.

Answer:- The oplog (operations log) is a capped collection that records all changes in a replica set for
replication.

Answer:-  Single field, compound, multikey, text, hashed, wildcard, and geospatial indexes.

Answer:- Through document-level locking and WiredTiger’s multi-version concurrency control (MVCC).

Answer:- $merge writes results to an existing collection, while $out replaces an entire collection with results.

Answer:- It redistributes data across shards to ensure balanced load.

Answer:- By selecting a good shard key that evenly distributes data and query load.

Answer:- The process of moving data between shards when rebalancing the cluster.

Answer: Using sh.status(), db.serverStatus(), and the MongoDB Atlas performance monitoring tools.

Answer: A secondary node that does not serve read queries and is used for backup or analytics.

Answer: To influence the election process of a primary node.

Answer: By building the new index in the background and then dropping the old one after validation.

Answer:  It improves performance by managing memory allocation between MongoDB and the OS.

Answer: Using the –auditDestination parameter to log user operations.

Answer: Ensures a transaction reads a consistent snapshot of the database, used in multi-document
transactions

Answer:  Occurs when a primary node steps down before its writes are replicated, causing data reversion.

Answer: A secondary node with a replication delay to maintain historical versions of data.

Answer: By enabling database profiling and checking the system.profile collection.

Answer:  A member of a replica set that participates in elections but does not store data

Answer: By stepping down the primary using rs.stepDown().

Answer: Backup config servers and shards separately, then restore in order: config servers first, then shards.

Answer: Provides real-time performance statistics of a MongoDB instance.

Answer: Use indexes, limit the use of $lookup, and apply $match early in the pipeline.

Answer:  collStats provides statistics on a collection, while dbStats gives database-level metrics.

Answer: By ensuring queries use indexes and avoiding regex searches without indexing.

Answer:  Queries for that shard’s data will fail unless the cluster is configured for partial results.

Answer: By running db.collection.find({ shardKey: { $exists: false } }).

Answer:  Allows automatic retry of write operations in case of transient failures.

Answer: By checking rs.printSlaveReplicationInfo() and monitoring network latency.

Answer: An index-building strategy that allows both foreground and background indexing approaches.

Answer: Restart the instance with –replSet and initialize the replica set using rs.initiate().

Answer: Determines how queries route to replica set members (e.g., primary, secondary, nearest).

Answer: By checking db.serverStatus().metrics.document and WiredTiger cache stats.

Answer: Uses an external LDAP service for user authentication.

Answer: Using db.collection.stats().

Answer: Ensures durability by logging write operations before applying them to data files.

Answer:  fsync flushes data to disk, while journaling writes changes to a log before applying them.

Answer:  Using mongodump/mongorestore or MongoDB Atlas live migration.

Answer: Randomly selects a specified number of documents from a collection.

Answer: UUID is a standard 128-bit unique identifier, while ObjectId is a 12-byte MongoDB-specific identifier.

Answer: Nodes vote based on priority and replication lag, and the node with the most votes becomes the
new primary

Answer:  A technique to ensure atomicity in distributed transactions using commit and abort phases.

Answer:  Using TTL indexes to automatically delete documents after a specified time.

Answer: Returns documents in the order they were stored in memory or disk.

Answer: By checking db.currentOp() and lock statistics in db.serverStatus().

Answer:  Monitors the time spent reading and writing data per collection.

Answer: Use write concerns, backups, and require confirmation for bulk delete operations

Placed Students//Partnership

Placed Students

For Frequent Course Updates and Information, Join our Telegram Group
Join 100% Placement Guranteed
 Programs

For Webinar Videos and Demo Session, Join our Youtube Channel