MongoDB Answers


0:00
0:00

MongoDB Answers

Basic MongoDB Answers

#QuestionAnswerExamples
1What is MongoDB?A NoSQL document databaseStores data in JSON-like documents
2What is a Document?A unit of data in MongoDB, containing key-value pairs (like JSON){ "_id": ObjectId(""), "name": "Alice", "age": 30 }
3What is a Collection?A group of related documents (similar to a table in SQL)A users collection containing user documents
4What is a Database?A container for collectionsA my_db database containing users and products collections
5What is BSON?Binary JSON; the serialization format MongoDB uses for documentsSupports more data types than standard JSON (e.g., Date, ObjectId)
6How do you connect to MongoDB?Using the mongosh shell or by connecting via an application drivermongosh "mongodb://localhost:27017"
7How do you create a database?Using the use command (it's created when the first data is inserted)use my_new_db;
8How do you create a collection?Using the db.createCollection() commanddb.createCollection("products");
9How do you insert a document?Using the insertOne() methoddb.users.insertOne({ name: "Bob", age: 25 });
10How do you insert multiple documents?Using the insertMany() methoddb.users.insertMany([{ name: "Charlie" }, { name: "David" }]);
11How do you find documents?Using the find() methoddb.users.find({ age: 30 });
12How do you find a single document?Using the findOne() methoddb.users.findOne({ name: "Alice" });
13How do you update documents?Using the updateOne() or updateMany() methodsdb.users.updateOne({ name: "Bob" }, { $set: { age: 26 } });
14How do you delete documents?Using the deleteOne() or deleteMany() methodsdb.users.deleteOne({ name: "Charlie" });
15What is the _id field?The primary key for each document, automatically generated if not provided{ "_id": ObjectId(""), "name": "Alice" }

Intermediate MongoDB Answers

#QuestionAnswerExamples
1What is embedding?Storing related data directly within a single documentA user document: { name: "Alice", address: { street: "123 Main St", city: "Anytown" } }
2What is referencing?Storing the _id of one document in another document (like a foreign key)An order document: { order_id: 123, user_id: ObjectId(""), items: [...] } (referencing a user's ID)
3When should you use embedding?When related data is accessed together, is small, and has a one-to-one or few relationshipEmbedding address details within a user document if they are always accessed together and don't change much.
4When should you use referencing?When related data is large, accessed independently, or has a one-to-many relationshipReferencing multiple orders from a user document, or referencing categories from a product document.
5What is the Aggregation Framework?A powerful tool for processing data and returning computed resultsdb.aggregate([ { $match: { age: { $gt: 25 } } }, { $group: { _id: "$city", count: { $sum: 1 } } } ])
6What is the $match stage in Aggregation?Filters documents based on specified criteria{ $match: { status: "active" } }
7What is the $group stage in Aggregation?Groups documents by a specified key and performs aggregation functions{ $group: { _id: "$category", count: { $sum: 1 } } }
8What is the $project stage in Aggregation?Reshapes documents, selecting or excluding fields, creating new fields{ $project: { _id: 0, userName: "$name", userEmail: "$email" } }
9What is the $sort stage in Aggregation?Sorts documents based on specified fields{ $sort: { timestamp: -1 } }
10What is the $lookup stage in Aggregation?Performs a left outer join to another collection{ $lookup: { from: "orders", localField: "\_id", foreignField: "user_id", as: "userOrders" } }
11How do you create an index?Using the db.collection.createIndex() methoddb.users.createIndex({ email: 1 });
12What is a unique index?Ensures the values in the indexed field are uniquedb.users.createIndex({ email: 1 }, { unique: true });
13What is a compound index?An index on multiple fieldsdb.products.createIndex({ category: 1, price: -1 });
14What is the explain() method?Provides details about how MongoDB executes a query (useful for performance analysis)db.users.find({ name: "Alice" }).explain("executionStats");
15What is Write Concern?Specifies the level of acknowledgment required for a write operation to be considered successfuldb.users.insertOne({...}, { writeConcern: { w: 2 } }); (acknowledgment from primary and one secondary if available)

Advanced MongoDB Answers

#QuestionAnswerExamples
1What is Sharding?Distributing data across multiple servers (shards) to handle large datasetsEach shard holds a subset of the data based on a shard key.
2What is a Shard Key?The field(s) used to determine which shard a document will be stored ondb.shardCollection("orders", { shardKey: { user_id: 1 } });
3What is a Replica Set?A group of MongoDB processes that maintain the same data set, providing high availability and redundancyOne primary node and multiple secondary nodes.
4What is Read Concern?Specifies the level of consistency required for a read operationdb.users.find({}, { readConcern: { level: 'local' } }); (can return slightly stale data)
5What is Read Preference?Specifies which node(s) in a replica set a read operation should target (e.g., primary, secondary)db.users.find({}, { readPreference: 'secondaryPreferred' }); (reads from secondary if available, otherwise primary)
6What are Transactions in MongoDB?Allows atomic, multi-document operations across multiple collections and shards (introduced in 4.0)const session = db.startSession(); session.startTransaction(); ... session.commitTransaction(); or session.abortTransaction();
7What is a TTL Index (Time-To-Live)?Automatically removes documents from a collection after a specified timedb.logs.createIndex({ logTime: 1 }, { expireAfterSeconds: 3600 }); (removes after 1 hour)
8What is a Text Index?Enables full-text search on string fieldsdb.products.createIndex({ description: "text", tags: "text" });
9What is MongoDB Atlas Search?A fully managed full-text search service built on Apache LuceneProvides advanced search capabilities beyond basic text indexes
10What are Change Streams?A mechanism to capture real-time data changes (inserts, updates, deletes) in a collectionAllows applications to receive notifications about data changes
11What is the Query Cache?Caches aggregated query results to improve read performancedb.coll.aggregate([...]).cache(...)
12How do you optimize MongoDB performance?Use appropriate indexes, optimize queries, consider embedding vs. referencing, use sharding/replica setsUse EXPLAIN, analyze query patterns, design efficient schemas
13What is the Write Journal?A mechanism where MongoDB stores data that is being written but not yet flushed to diskEnsures data durability in case of crashes during a write operation
14What is Oplog (Operation Log)?A capped collection in a replica set that records all operations performed on the primary nodeUsed by secondary nodes to replicate changes from the primary
15What is a Capped Collection?A collection with a fixed maximum size or number of documents; older documents are automatically removeddb.createCollection("logs", { capped: true, size: 1000000 }); (1MB size)

Last updated on July 30, 2025

🔍 Explore More Topics

Discover related content that might interest you

TwoAnswers Logo

Providing innovative solutions and exceptional experiences. Building the future.

© 2025 TwoAnswers.com. All rights reserved.

Made with by the TwoAnswers.com team