Title: Nosql MongoDB — LearnCoachAssist

Q: What is MongoDB?
A: MongoDB is a NoSQL document-oriented database that stores data in flexible, JSON-like documents called BSON. It is designed for scalability and high performance, making it ideal for applications with rapidly evolving schemas and large volumes of unstructured or semi-structured data.

Q: What is the document model in MongoDB?
A: The document model stores data as documents, which are rich data structures similar to JSON objects. Each document can contain nested fields, arrays, and sub-documents, allowing related data to be stored together rather than spread across multiple tables as in relational databases.

Q: What is BSON?
A: BSON (Binary JSON) is the binary-encoded serialization format MongoDB uses to store documents and make remote procedure calls. It extends JSON with additional data types such as Date, ObjectId, int, long, double, and binary, enabling efficient storage and traversal.

Q: What is an ObjectId in MongoDB?
A: An ObjectId is a 12-byte unique identifier automatically generated by MongoDB as the default _id field for each document. It consists of:
- A 4-byte timestamp
- A 5-byte random value
- A 3-byte incrementing counter
ObjectIds are sortable by creation time.

Q: How do you insert a document in MongoDB?
A: Use db.collection.insertOne() for a single document or db.collection.insertMany() for multiple documents. Example: db.users.insertOne({ name: "Alice", age: 30 }). MongoDB automatically adds an _id field if not provided.

Q: How do you query documents in MongoDB?
A: Use db.collection.find(filter, projection) to query documents. Example: db.users.find({ age: { $gt: 25 } }) returns all users older than 25. Use findOne() to return only the first matching document.

Q: What are the basic CRUD operations in MongoDB?
A: MongoDB CRUD operations are:
- Create: insertOne(), insertMany()
- Read: find(), findOne()
- Update: updateOne(), updateMany(), replaceOne()
- Delete: deleteOne(), deleteMany()

Q: What are MongoDB query operators?
A: MongoDB provides query operators for filtering:
- Comparison: $eq, $ne, $gt, $gte, $lt, $lte, $in, $nin
- Logical: $and, $or, $not, $nor
- Element: $exists, $type
- Array: $all, $elemMatch, $size

Q: How do you update documents in MongoDB?
A: Use db.collection.updateOne(filter, update) or updateMany(). Update operators include $set (set fields), $unset (remove fields), $inc (increment), $push (add to array), and $pull (remove from array). Example: db.users.updateOne({ name: "Alice" }, { $set: { age: 31 } }).

Q: What is the aggregation pipeline in MongoDB?
A: The aggregation pipeline processes documents through a sequence of stages, each transforming the data. Common stages include $match (filter), $group (aggregate), $project (reshape), $sort, $limit, and $lookup (join). It is MongoDB's primary tool for complex data analysis and transformation.

Q: What does the $match stage do in the aggregation pipeline?
A: The $match stage filters documents based on specified conditions, similar to a find() query. It should be placed early in the pipeline to reduce the number of documents processed by subsequent stages. Example: { $match: { status: "active" } }.

Q: What does the $group stage do in the aggregation pipeline?
A: The $group stage groups documents by a specified _id expression and applies accumulator operators like $sum, $avg, $min, $max, $push, and $first. Example: { $group: { _id: "$category", total: { $sum: "$price" } } }.

Q: What does the $project stage do?
A: The $project stage reshapes documents by including, excluding, or computing new fields. Use 1 to include a field, 0 to exclude it, or an expression to create a computed field. Example: { $project: { fullName: { $concat: ["$first", " ", "$last"] }, _id: 0 } }.

Q: What does the $lookup stage do?
A: The $lookup stage performs a left outer join with another collection, similar to a SQL JOIN. It requires from (target collection), localField, foreignField, and as (output array field). Example: { $lookup: { from: "orders", localField: "_id", foreignField: "userId", as: "userOrders" } }.

Q: What does the $unwind stage do?
A: The $unwind stage deconstructs an array field, creating a separate document for each element. For example, if a document has tags: ["a", "b", "c"], { $unwind: "$tags" } produces three documents, each with a single tag value. Use preserveNullAndEmptyArrays: true to keep documents with missing or empty arrays.

Q: What is indexing in MongoDB?
A: Indexing improves query performance by creating efficient data structures (B-tree) that allow MongoDB to locate documents without scanning the entire collection. Without indexes, MongoDB performs a collection scan. Indexes consume additional storage and memory, and slow down write operations, so they should be created strategically.

Q: What is a single field index in MongoDB?
A: A single field index is created on one field of a document. Example: db.users.createIndex({ email: 1 }) creates an ascending index on the email field. The value 1 means ascending, -1 means descending. MongoDB automatically creates a single field index on the _id field.

Q: What is a compound index in MongoDB?
A: A compound index includes multiple fields in a single index. Example: db.orders.createIndex({ userId: 1, createdAt: -1 }). The order of fields matters — compound indexes support queries that match a prefix of the index fields. They follow the ESR rule: Equality, Sort, Range for optimal field ordering.

Q: What is a text index in MongoDB?
A: A text index supports full-text search on string content. Create one with db.articles.createIndex({ content: "text" }). Query using $text and $search: db.articles.find({ $text: { $search: "mongodb tutorial" } }). Each collection can have at most one text index, but it can cover multiple fields.

Q: What is a TTL index in MongoDB?
A: A TTL (Time-To-Live) index automatically removes documents after a specified number of seconds. It is created on a field containing a Date value: db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 }). TTL indexes are useful for session data, logs, and temporary records.

Q: What is a multikey index in MongoDB?
A: A multikey index is automatically created when you index a field that holds an array. MongoDB creates separate index entries for each element of the array. For example, indexing { tags: 1 } on a document with tags: ["A", "B"] creates entries for both values. A compound index cannot include more than one array field.

Q: How do you use the explain() method?
A: The explain() method provides information about query execution plans. Use db.collection.find(query).explain("executionStats") to see details including whether an index was used (IXSCAN vs COLLSCAN), documents examined, and execution time. This is essential for query optimization.

Q: What is a covered query in MongoDB?
A: A covered query is one that can be satisfied entirely using an index without examining any documents. This happens when both the query filter and the projection include only indexed fields. Covered queries are extremely fast because they avoid reading from disk. Use explain() to verify with totalDocsExamined: 0.

Q: What is a replica set in MongoDB?
A: A replica set is a group of MongoDB instances that maintain the same data set for high availability. It consists of a primary node (handles writes) and one or more secondary nodes (replicate data from the primary). If the primary fails, an automatic election promotes a secondary to primary.

Q: How does replication work in MongoDB?
A: The primary node records all write operations in its oplog (operations log). Secondary nodes continuously replicate by tailing the oplog and applying operations locally. Replication provides data redundancy, high availability through automatic failover, and the ability to distribute read operations across secondaries.

Q: What is an arbiter in a replica set?
A: An arbiter is a replica set member that participates in elections but does not hold data. It is used to break ties during primary election when you have an even number of data-bearing members. Arbiters are lightweight and require minimal resources, but should be used sparingly in production environments.

Q: What is write concern in MongoDB?
A: Write concern specifies the level of acknowledgment requested from MongoDB for write operations. Options include:
- w: 0 — no acknowledgment
- w: 1 — acknowledged by primary (default)
- w: "majority" — acknowledged by majority of replica set members
Higher write concern increases durability but adds latency.

Q: What is read preference in MongoDB?
A: Read preference determines which replica set members receive read operations. Options include:
- primary — reads from primary only (default)
- primaryPreferred — primary, fallback to secondary
- secondary — reads from secondaries only
- secondaryPreferred — secondary, fallback to primary
- nearest — lowest latency member

Q: What is sharding in MongoDB?
A: Sharding is MongoDB's horizontal scaling strategy that distributes data across multiple servers called shards. Each shard holds a subset of the data based on a shard key. Sharding allows MongoDB to handle large data sets and high throughput by spreading the load across multiple machines.

Q: What are the components of a sharded cluster?
A: A MongoDB sharded cluster consists of:
- Shards — store the actual data (each shard is a replica set)
- Config servers — store metadata and configuration for the cluster
- mongos — query routers that direct operations to the appropriate shards

Q: What is a shard key?
A: A shard key is an indexed field or compound fields that MongoDB uses to distribute documents across shards. Choosing a good shard key is critical — it should have high cardinality, low frequency, and distribute writes evenly. A poor shard key leads to hot spots where one shard handles most of the traffic.

Q: What is the difference between embedded and referenced documents?
A: Embedded documents store related data within a single document (denormalized), ideal for one-to-few relationships and data read together. Referenced documents store relationships using ObjectId references (normalized), better for one-to-many or many-to-many relationships. Embedding provides faster reads; referencing provides data consistency and smaller document sizes.

Q: When should you embed documents vs reference them?
A: Embed when:
- Data is always accessed together
- One-to-few relationship
- Data doesn't change frequently
Reference when:
- Data is accessed independently
- One-to-many or many-to-many relationship
- Document size might exceed 16MB limit
- Data is updated frequently

Q: What is the maximum document size in MongoDB?
A: The maximum BSON document size in MongoDB is 16 megabytes. This limit ensures that a single document cannot use excessive memory or bandwidth. For storing files larger than 16MB, MongoDB provides GridFS, which splits files into smaller chunks stored as separate documents.

Q: What is GridFS in MongoDB?
A: GridFS is a specification for storing and retrieving files that exceed the 16MB BSON document size limit. It stores files in two collections: fs.files (metadata) and fs.chunks (binary data in 255KB chunks). GridFS is useful for storing images, videos, audio, and other large files.

Q: What are MongoDB transactions?
A: MongoDB supports multi-document ACID transactions starting from version 4.0 (replica sets) and 4.2 (sharded clusters). Transactions ensure atomicity across multiple operations and collections. Use session.startTransaction(), perform operations, then session.commitTransaction() or session.abortTransaction().

Q: What are change streams in MongoDB?
A: Change streams allow applications to access real-time data changes without polling the oplog. They provide a subscription-based API: db.collection.watch() returns a cursor that emits events for inserts, updates, deletes, and replacements. Change streams are useful for triggering actions, syncing data, and building event-driven architectures.

Q: What is MongoDB Atlas?
A: MongoDB Atlas is the fully managed cloud database service by MongoDB, available on AWS, Azure, and Google Cloud. It provides automated provisioning, scaling, backup, monitoring, and security features. Atlas includes a free tier (M0) for development and offers features like Atlas Search, Data Lake, and Charts.

Q: What is mongosh?
A: mongosh (MongoDB Shell) is the modern command-line interface for interacting with MongoDB. It replaces the legacy mongo shell and offers syntax highlighting, intelligent autocomplete, and built-in help. It supports JavaScript and can run scripts: mongosh --eval "db.users.countDocuments()".

Q: How does MongoDB compare to SQL databases?
A: Key differences:
- Data model: MongoDB uses documents; SQL uses tables with rows and columns
- Schema: MongoDB is schema-flexible; SQL enforces a fixed schema
- Joins: MongoDB uses $lookup and embedding; SQL uses JOIN
- Scaling: MongoDB scales horizontally via sharding; SQL typically scales vertically
- Transactions: Both support ACID, but SQL has more mature transaction support

Q: What are capped collections in MongoDB?
A: Capped collections are fixed-size collections that automatically overwrite the oldest documents when the size limit is reached. They maintain insertion order and support high-throughput operations. Create with: db.createCollection("logs", { capped: true, size: 1048576, max: 1000 }). They are ideal for logs and cache-like use cases.

Q: What is the $set operator in MongoDB?
A: The $set operator replaces the value of a field or creates it if it doesn't exist. Example: db.users.updateOne({ _id: 1 }, { $set: { name: "Bob", "address.city": "NYC" } }). It can update top-level fields, nested fields using dot notation, and array elements by index.

Q: What is the $push operator in MongoDB?
A: The $push operator appends a value to an array field. Example: db.posts.updateOne({ _id: 1 }, { $push: { tags: "mongodb" } }). Modifiers include $each (push multiple), $sort (sort array after push), $slice (limit array size), and $position (insert at index).

Q: What is the $addToSet operator?
A: The $addToSet operator adds a value to an array only if it doesn't already exist, preventing duplicates. Example: db.users.updateOne({ _id: 1 }, { $addToSet: { roles: "admin" } }). Use $each with $addToSet to add multiple unique values at once.

Q: What is MongoDB Compass?
A: MongoDB Compass is the official GUI for MongoDB. It provides a visual interface for exploring data, building queries, viewing and optimizing query plans with explain(), managing indexes, and validating schema. It includes an aggregation pipeline builder that helps construct complex pipelines stage by stage.

Q: What are wildcard indexes in MongoDB?
A: Wildcard indexes (introduced in v4.2) index all fields or a subset of fields with dynamic or unknown names. Create with db.data.createIndex({ "$**": 1 }) to index all fields, or db.data.createIndex({ "metadata.$**": 1 }) to index all subfields of metadata. They are useful for polymorphic schemas.

Q: What is the bucket pattern in MongoDB schema design?
A: The bucket pattern groups related data into fixed-size "buckets" within a single document. For time-series data, instead of one document per measurement, you store multiple measurements in an array within a single document (e.g., one document per hour). This reduces document count, improves read performance, and optimizes storage.

Q: What is the polymorphic pattern in MongoDB?
A: The polymorphic pattern stores documents with different shapes in the same collection, using a discriminator field (e.g., type) to distinguish them. For example, a products collection might contain both { type: "book", author: "..." } and { type: "movie", director: "..." }. This leverages MongoDB's flexible schema.

Q: What is the attribute pattern in MongoDB?
A: The attribute pattern restructures documents with many similar fields into an array of key-value pairs. Instead of { color: "red", size: "L", weight: 5 }, use { attributes: [{ k: "color", v: "red" }, { k: "size", v: "L" }] }. This allows indexing on { "attributes.k": 1, "attributes.v": 1 } to support queries on any attribute efficiently.

Q: How do you perform a text search in MongoDB?
A: First create a text index: db.articles.createIndex({ title: "text", body: "text" }). Then search: db.articles.find({ $text: { $search: "mongodb performance" } }). Use $meta: "textScore" to sort by relevance. For advanced full-text search, consider Atlas Search which uses Apache Lucene under the hood.