Chapter 2: Document Databases using MongoDB Unit II - NoSQL Databases B.Tech - Computer Science / Information Science / Information Technology - Semester V NoSQL Databases A Comprehensive Undergraduate Textbook CHAPTER 2 Document Databases using MongoDB Unit II: Document Databases using MongoDB Sections Covered 2.1 Paradigm Overview 2.2 Environment Setup 2.3 Practical Operations 2.4 Advanced MongoDB Architecture Chapter 2: Document Databases using MongoDB Unit II - NoSQL Databases Table of Contents Chapter Introduction / Overview Learning Outcomes Key Concepts 2.1 Paradigm Overview 2.1.1 Core Document Database Features 2.1.2 MongoD B Specific Advantages 2.2 Environment Setup 2.2.1 Installing MongoDB 2.2.2 Connecting to MongoDB 2.3 Practical Operations 2.3.1 Basic CRUD Operations 2.3.2 Working with the Mongo Shell 2.4 Advanced MongoDB Architecture 2.4.1 Data Modelling Principles 2.4.2 Indexing Strategies 2.4.3 The Aggregation Framework Further Reading / Viewing Assessment Questions Chapter 2: Document Databases using MongoDB Chapter Introduction / Overview Document databases are a major category of NoSQL databases. They store data as flexible, self - describing documents instead of strict rows and columns. Each document contains field - and - value pairs, and the values may include strings, numbers, dates, arrays, embedded documents and other supported data types. MongoDB is one of the most widely used document database systems. It stores records as BSON documents, which are binary representations of JSON - like documents. This makes MongoDB useful for applications where data is naturally hierarchical, frequently changing or closely connected t o objects used in programming languages. In a relational database, data is usually divided into normalized tables and connected using joins. In MongoDB, related data can often be embedded inside the same document so that an application can retrieve require d information in a single query. This style of design can improve developer productivity, but it also requires careful modelling decisions. This chapter introduces document database concepts, MongoDB installation and connection methods, CRUD operations, th e MongoDB Shell, data modelling principles, indexing strategies and the aggregation framework. The examples are written for beginners and use a simple college database scenario so that students can understand both theory and practice. Learning Outcomes Upo n successful completion of this chapter, students will be able to: 1. Define document databases and explain how they differ from relational databases. 2. Describe the structure of MongoDB databases, collections and BSON documents. 3. Identify core document database features such as schema flexibility, embedded documents, arrays, indexing and aggregation. 4. Install MongoDB Community Edition or use MongoDB Atlas for cloud - based practice. 5. Connect to MongoDB using MongoDB Shell, Compass or connection string s. Chapter 2: Document Databases using MongoDB Unit II - NoSQL Databases 6. Perform basic CRUD operations using mongosh commands. 7. Apply simple data modelling rules such as embedding, referencing and access - pattern based design. 8. Explain the purpose of indexes and select suitable indexing strategies for common queries. 9 . Use the aggregation framework to filter, group, sort and reshape data. 10. Analyse basic performance and design trade - offs in MongoDB applications. Key Concepts Glossary of Key Terms in This Chapter Term Meaning Document Database A NoSQL database model that stores records as documents containing field - and - value pairs. MongoDB A document - oriented NoSQL database that stores data records as BSON documents. BSON Binary JSON; MongoDB uses BSON to represent documents internally and support additional data types. Database A logical container that holds collections. Collection A group of MongoDB documents, similar to a table in a relational database but without a fixed row schema. Document A single record made of fields and values, often similar to a JSON object. CRUD Create, Read, Update and Delete operations performed on documents. mongosh The MongoDB Shell used to connect to MongoDB and execute commands interactively. Index A data structure that improves query performance by allowing faster lookup of documents. Aggregation Pipeline A sequence of stages that processes documents and returns computed or transformed results. Embedding Storing related data inside the same document. Referencing Storing a link or identifier to related data stored in anothe r collection. 2.1 Paradigm Overview The document database paradigm is built around the idea that many real - world entities can be represented as structured documents. For example, a student record may include personal details, address, course details, marks and skills. Instead of splitting all of this data into separate tables, a document database can store much of it together in one document. This model is especially useful for modern applications such as e - commerce, learning management systems, mobile apps, content management systems, healthcare records, IoT systems and user profile management. These applications often handle data that changes over time and may not fit neatly into a fixed table structure. Chapter 2: Document Databases using MongoDB Unit II - NoSQL Databases Figure 2.1: Database, collection and document structure in MongoDB. 2.1.1 Core Document Database Features Document databases have several features that make them different from traditional relational systems. The following table summarizes the most important features from a beginner point of view. Fe ature Description Example / Importance Document - based storage Data is stored as documents containing fields and values. A student document can store name, department, address and marks together. Flexible schema Documents in the same collection do not always need identical fields. One student may have internship details while another may not. Nested documents Documents can contain other documents as field values. address: { city: "Bengaluru", pin: 560001 } Arrays Fields can store lists of values or li sts of documents. skills: ["Python", "MongoDB", "Testing"] Natural object mapping Documents closely resemble objects used in programming languages. A JavaScript object can be stored with minimal transformation. Ad hoc querying Users can query based on fields, ranges, patterns and conditions. Find students with score greater than 80. Indexing Indexes speed up frequently used queries. Index on department improves department - based searches. Aggregation Data can be filtered, grouped, sorted and summarized inside the database. Calculate average marks department - wise. Horizontal scaling Many document databases support distributed storage. Large datasets can be spread across multiple servers using sharding. Chapter 2: Document Databases using MongoDB Unit II - NoSQL Databases Did You Know? A MongoDB document looks similar to JSON, but MongoDB stores it internally as BSON. BSON supports more data types than plain JSON, such as ObjectId and date values. Document Database versus Relational Database Dimension Relational Database Document Database / MongoDB Data unit Row in a table. Document in a collection. Structure Fixed schema with columns and data types. Flexible document structure. Relationships Often managed using foreign keys and joins. Managed using embedding or references. Best suited for Highly structured data with strong consistency and complex transactions. Flexible, hierarchical and rapidly changing data. Query style SQL queries. MongoDB Query Language and aggregation pipelines. Scaling pattern Can scale vertically and horizontally depending on system. Designed with distributed scaling options such as replication and sharding. 2.1.2 MongoDB Specific Advantages MongoDB is popular because it combines the flexibility of a document model with practical tools for application development, indexing, aggregati on, replication and cloud deployment. It is suitable for both classroom experiments and real - world applications. MongoDB Advantage Explanation Classroom / Project Use Flexible document model Documents can store nested and variable data structures. Useful for student profiles, product catalogs and event records. Developer - friendly syntax MongoDB documents resemble JSON objects used in web programming. Students can easily understand records and queries. Powerful query language Supports filtering, comparison operators, logical operators and projection. Useful for searching by department, marks, city or status. Secondary indexes Indexes can be created on commonly searched fields. Improves speed of repeated queries. Aggregation framework Allows grou ping, summarizing and transforming data. Useful for reports such as average marks by department. Tools ecosystem MongoDB Shell, Compass, Atlas and drivers support development. Students can practice using GUI, shell and programming languages. Distributed features Supports replica sets for high availability and sharding for horizontal scaling. Introduces modern database architecture concepts. Best Practice Use MongoDB when the document model matches how the application reads and writes data. Do not choose MongoDB only because it is NoSQL; choose it when flexible documents, nested data and scalable access patterns are useful. Chapter 2: Document Databases using MongoDB Unit II - NoSQL Databases 2.2 Environment Setup Before performing MongoDB operations, students need a running MongoDB deployment and a tool to connect to it. The deployment may be local MongoDB Community Edition installed on a computer, or a cloud cluster created using MongoDB Atlas. For beginner laboratory work, either option is acceptable. Figure 2.5: A simplified MongoDB application architecture. 2.2.1 In stalling MongoDB MongoDB can be installed locally using MongoDB Community Edition. The exact steps depend on the operating system, so students should always verify the latest installation commands from the official MongoDB documentation before installing. Installation Option What It Means When to Use MongoDB Community Edition Free self - managed MongoDB server installed on a local computer or lab machine. Best for offline labs, local practice and understanding server processes. MongoDB Atlas Fully managed MongoDB cloud service. Best when students do not want to install a local database server. MongoDB Compass Graphical user interface for browsing databases and running queries. Best for beginners who prefer visual exploration. MongoDB Shell (mongosh) Comma nd - line shell for connecting and running MongoDB commands. Best for learning CRUD commands and database syntax. General Local Installation Steps 1. Visit the official MongoDB Community Server download or installation documentation page. 2. Select the correct operating system such as Windows, Ubuntu, macOS or another supported platform. 3. Download and install MongoDB Community Server using the installer or package manager instructions. 4. Install MongoDB Shell if it is not included or if a separate she ll installation is required. 5. Start the MongoDB server service. On many systems the service name is mongod. 6. Open a terminal or command prompt and run mongosh to connect to the server. Chapter 2: Document Databases using MongoDB Unit II - NoSQL Databases 7. Verify the connection by running commands such as show dbs and d b.version(). # Example verification commands inside mongosh show dbs db.version() db.stats() Laboratory Tip For college labs, install MongoDB Community Server and mongosh before the lab session begins. Also create one sample database folder or use the default service configuration so students can start practicing quickly. 2.2.2 Connecting to MongoDB A connection string tells tools and applications where the MongoDB deployment is located and how to connect to it. Local connections commonly use mongodb://localhost:27017. Cloud clusters often use mongodb+srv:// connection strings. Connection Method Example Purpose Local mongosh mongosh Connects to the default local MongoDB server. Explicit local URI mongosh "mongodb://localhost:27017" Connects t o a local server using a URI. Atlas SRV URI mongosh "mongodb+srv://cluster - url" Connects to a MongoDB Atlas cluster. Application driver MongoClient("mongodb://localhost:27017") Allows programs to connect from Python, Node.js, Java and other languages. Compass GUI Paste the connection string in MongoDB Compass. Connects through a graphical interface. # Start MongoDB Shell and connect to local MongoDB mongosh # Connect using a local connection string mongosh "mongodb://localhost:27017" # Common beginn er commands after connecting show dbs use collegeDB show collections Important Point Use mongodb+srv:// for SRV connection strings, commonly used by Atlas clusters. Use mongodb:// for standard connection string s such as local servers or explicitly listed hosts. 2.3 Practical Operations Practical MongoDB work begins with CRUD operations. CRUD stands for Create, Read, Update and Delete. These operations allow a user to insert documents, retrieve documents, modify existing documents and remove unwant ed documents from a collection. Chapter 2: Document Databases using MongoDB Unit II - NoSQL Databases Figure 2.2: CRUD operations form the basic workflow for interacting with documents. 2.3.1 Basic CRUD Operations (Create, Read, Update, Delete) Preparing a Sample Database The following examples use a database named collegeDB and a collection named students. In mongosh, the use command switches to a database. If the database does not exist, it is created when data is inserted. use collegeDB db.students.insertMany([ { name: "Asha", department: "CSE", sem ester: 5, city: "Mysuru", marks: { dbms: 86, python: 92 }, skills: ["Python", "MongoDB"] }, { name: "Ravi", department: "ISE", semester: 5, city: "Bengaluru", marks: { dbms: 78, python: 81 }, skills: ["Java", "Testin g"] }, { name: "Meena", department: "CSE", semester: 3, city: "Hubballi", marks: { dbms: 91, python: 88 }, skills: ["Python", "Data Analysis"] } Chapter 2: Document Databases using MongoDB Unit II - NoSQL Databases ]) Create Operations Create operations add new documents to a collection. MongoDB provides insertOne() for one document and insertMany() for multiple documents. If the target collection does not exist, MongoDB creates it during insertion. Method Purpose Example Use insertOne() Inserts a single document. Add one new student. insertMany() Inserts multiple documents at once. Add a batch of students. db.students.insertOne({ name: "Kiran", department: "ECE", semester: 5, city: "Dharwad", marks: { dbms: 74, python: 69 }, skills: ["C", "Electronics"] }) Read Operati ons Read operations retrieve documents from a collection. The find() method can return multiple matching documents, while findOne() returns a single matching document. Conditions are written as query documents. Query Need MongoDB Command Meaning All students db.students.find() Displays every document in the students collection. One CSE student db.students.findOne({ department: "CSE" }) Returns one matching CSE document. Marks greater than 80 db.students.find({ "marks.dbms": { $gt: 80 } }) Uses comparison operator $gt. Only selected fields db.students.find({}, { name: 1, department: 1, _id: 0 }) Uses projection to show selected fields. Sort by name db.students.find().sort({ name: 1 }) Sorts ascending by name. // Read all documents db.students .find() // Display in a readable format db.students.find().pretty() // Find CSE students from semester 5 db.students.find({ department: "CSE", semester: 5 }) // Find students whose DBMS marks are greater than 80 db.students.find({ "marks.dbms": { $gt: 8 0 } }) // Projection: show only name and department db.students.find({}, { name: 1, department: 1, _id: 0 }) Chapter 2: Document Databases using MongoDB Unit II - NoSQL Databases Update Operations Update operations modify existing documents. updateOne() changes the first matching document, and updateMany() changes all matching documents. The $set operator is commonly used to change or add fields without replacing the entire document. Method / Operator Purpose Example updateOne() Updates one matching document. Change one student city. updateMany() Updates all matching documents. Add mentor field to all CSE students. $set Sets or changes a field value. { $set: { city: "Mysuru" } } $inc Increments a numeric value. { $inc: { semester: 1 } } $push Adds an item to an array. { $push: { skills: "AI" } } // Update one document db.students.updateOne( { name: "Ravi" }, { $set: { city: "Mangaluru" } } ) // Update many documents db.students.updateMany( { department: "CSE" }, { $set: { mentor: "Dr. Rao" } } ) // Add a new skill to one student's skills array db.stud ents.updateOne( { name: "Asha" }, { $push: { skills: "Cloud" } } ) Delete Operations Delete operations remove documents from a collection. deleteOne() removes the first matching document. deleteMany() removes all matching documents. Students should use delete operations carefully because removed documents may not be recoverable unless backups are available. // Delete one matching document db.students.deleteOne({ name: "Kiran" }) // Delete all students from a city db.students.deleteMany({ city: "Hubballi" }) // Count remaining documents db.students.countDocuments() Chapter 2: Document Databases using MongoDB Unit II - NoSQL Databases Safety Tip Always test the filter first using find() before running updateMany() or deleteMany(). This helps avoid accidental modificati on or deletion of many documents. 2.3.2 Working with the Mongo Shell MongoDB Shell, also called mongosh, is an interactive command - line interface for MongoDB. It is useful for learning commands, testing queries, managing databases and running administrative operations. Beginners should become co mfortable with shell navigation commands before writing application programs. mongosh Command Purpose show dbs Displays available databases. use databaseName Switches to a database. Creates it when data is inserted. show collections Displays collections in the current database. db Shows the current database name. db.collection.find() Reads documents from a collection. db.collection.countDocuments() Counts documents in a collection. db.collection.drop() Drops a collection. db.dropDatabase() Deletes the current database. cls Clears the shell screen in many terminals. exit Exits the shell. Common Beginner Shell Session // 1. Start shell mongosh // 2. View databases show dbs // 3. Switch to a database use collegeDB // 4. Insert a sample document db.students.insertOne({ name: "Sneha", department: "AIML", semester: 5 }) // 5. View collections show collections // 6. Read documents db.students.find() // 7. Count documents db.students.countDocuments() Chapter 2: Document Databases using MongoDB Unit II - NoSQL Databases Note mongosh commands are JavaScript - like. Collection methods such as find(), insertOne(), updateOne() and deleteOne() are written with parentheses and usually receive query documents as arguments. 2.4 Advanced MongoDB Architecture Advanced MongoDB architecture includes data modelling, indexing, aggregation, replication and sharding. In this unit, the focus is on three architecture concepts that directly affect how applications store and retrieve data: data modelling, indexi ng and aggregation. 2.4.1 Data Modelling Principles Data modelling means d eciding how data will be organized inside the database. In MongoDB, good data modelling starts with access patterns. This means the designer should first ask: What data will the application read together? What data will be updated frequently? Which queries must be fast? Principle Meaning Example Model for application queries Design documents based on how the application reads and writes data. Store recent product reviews with product data if they are always shown together. Store related data together when appropriate Use embedding when data is commonly accessed as one unit. Store address inside a student document. Use references for large or independent data Store related data in separate collections and link using IDs. Store all exam attempts separately if the list grows too large. Avoid unlimited array growth Very large arrays inside one document can become inefficient. Do not store thousands of log entries inside a single user document. Keep frequently updated data separate when needed Heavy updates to one part of a document can affect performance. Separate live attendance logs from static student profile data. Use schema validation when required MongoDB can enforce rules for fields and data types. Require name, department and semester for student re cords. Embedding versus Referencing Design Choice Use When Advantages Precautions Embedding Related data is read together and has a bounded size. Fast single - document reads; natural document structure. Avoid very large documents or unbounded arrays. Referencing Related data is large, shared or frequently updated independently. Reduces duplication and separates large datasets. May require multiple queries or aggregation lookup. // Embedded design: address is stored inside student document { name: "Asha", department: "CSE", address: { city: "Mysuru", pin: 570001 } } // Referenced design: student document stores departmentId { Chapter 2: Document Databases using MongoDB Unit II - NoSQL Databases name: "Asha", departmentId: ObjectId("...") } Important Design Rule In MongoDB, data that is accessed tog ether should generally be stored together. However, if related data grows without limit or is updated independently, referencing may be a better design. 2.4.2 Indexing Strategies Indexes are special data structures that make queries faster. Without an index, MongoDB may need to scan every document in a collection to find matches. With a suitable index, MongoDB can locate matching documents more efficiently. Figure 2.3: An index helps MongoDB avoid scanning every document for common queries. Index Type Purpose Example Command Single - field index Supports queries on one field. db.students.createIndex({ department: 1 }) Compound index Supports queries using multiple fields in a defined order. db.students.createIndex({ department: 1, semester: 1 }) Multikey index Indexes values inside an array field. db.students.createIndex({ skills: 1 }) Text index Supports text search on string content. db.articles.createIndex({ title: "text", body: "text" }) Unique index Prevents duplicate values for a field. db.students.createIndex({ usn: 1 }, { unique: true }) Creating and Viewing Indexes // Create a single - field index db.students.createIndex({ department: 1 }) Chapter 2: Document Databases using MongoDB Unit II - NoSQL Databases // Create a compound index db.students.createIndex({ department: 1, semester: 1 }) // Create an index on an array field db.students.createIndex({ skills: 1 }) // View existing indexes db.students.getIndexes() // Drop an index by name db.students.dropIndex("department_1") Indexing Strategy Rules 1. Create indexes for fields used frequently in fi lters, sorting and joins/lookups. 2. Use compound indexes when queries commonly use multiple fields together. 3. Choose compound index field order carefully. The first field and prefix fields are important for query support. 4. Avoid creating too many inde xes because each index uses storage and slows down write operations. 5. Use explain() to check whether a query is using an index. 6. Remove unused indexes after analysing workload and performance needs. // Analyse query execution db.students.find({ depart ment: "CSE" }).explain("executionStats") Best Practice Indexes improve read performance but add overhead to insert, update and delete operations because MongoDB must maintain the index structures. Create indexes based on real query requirements. 2.4.3 The Aggregation Framework The aggregation framework processes documents through a pipeline of stages. Each stage receives input documents, performs an operation and passes the result to the next stage. Aggregation is used for reporting, analytics, groupin g, filtering, sorting and reshaping documents. Chapter 2: Document Databases using MongoDB Unit II - NoSQL Databases Figure 2.4: Aggregation pipeline stages process documents step by step. Stage Purpose Example Use $match Filters documents based on conditions. Select only CSE students. $project Selects, removes or reshapes fields. Show name and total marks only. $group Groups documents and computes totals, averages, counts and other values. Average DBMS marks department - wise. $sort Sorts documents. Sort departments by average marks. $limit Limits number of output documents. Show top five results. $unwind Breaks array values into separate documents. Process each skill separately. $lookup Performs left outer join - like operation with another collection. Connect students with department details. Example 1: Department - wise Average Marks db.students.aggregate([ { $group: { _id: "$department", averageDBMS: { $avg: "$marks.dbms" }, totalStudents: { $sum: 1 } }}, { $sort: { averageDBMS: - 1 } } ]) Explanation: The $group stage groups students based on department. The $avg operator calculates average DBMS marks, and $sum counts the number of students. The $sort stage arranges the result from highest average to lowest average. Chapter 2: Document Databases using MongoDB Unit II - NoSQL Databases Example 2: Filter, Project and Sort db.students.aggregate([ { $match: { semester: 5 } }, { $project: { _id: 0, name: 1, department: 1, totalMarks: { $add: ["$marks.dbms", "$marks.python"] } }}, { $sort: { totalMarks: - 1 } } ]) Explanation: This pipeline first selects fifth - semester students, then creates a new computed field called totalMarks, and finally sorts the output in descending order of total marks. Example 3: Working with Array Data db.students.aggregate([ { $unwind: "$skills" }, { $group: { _id: "$skills", numberOfStudents: { $sum: 1 } }}, { $sort: { numberOfStudents: - 1 } } ]) Explanation: $unwind separates each skill in the skills array into an individual pipeline item. Then $group counts how many students have each skill. Remember Aggregation pipel ines usually do not modify the original documents. However, special stages such as $merge or $out can write results to a collection, so use them carefully. 2.4.4 Performance Analysis for Beginner MongoDB Designs Performance in MongoDB depends on document design, query shape, index availability, working set size and server resources. A good beginner design keeps commonly read data together, avoids unbounded document growth, and indexes fields used by frequent queries. Performance Factor Good Practice Probl em if Ignored Document design Store related bounded data together. Too many queries or very large documents. Indexes Create indexes for frequent filters and sorts. Slow collection scans. Projection Return only fields needed by the application. Unnecessary network and memory use. Aggregation order Place selective $match stages early when possible. More documents processed in later stages. Array design Keep arrays bounded or separate large events into another collection. Document growth and upda te overhead. Write workload Avoid excessive indexes on write - heavy collections. Slower inserts and updates. Chapter 2: Document Databases using MongoDB Unit II - NoSQL Databases Chapter Summary Document databases store records as flexible documents instead of fixed rows and columns. MongoDB organizes data into databases, collections and BSON documents. MongoDB supports CRUD operations through methods such as insertOne(), find(), updateOne() and deleteOne(). mongosh is an important tool for interactive MongoDB practice. Good MongoDB data modelling depends on application acc ess patterns. Embedding is useful when related data is read together and has a bounded size; referencing is useful when related data is large or independent. Indexes improve query performance but add storage and write overhead. Aggregation pipelines proces s documents through stages such as $match, $group, $sort and $project. 2.5 Further Reading / Viewing The following resources are recommended for students who want to strengthen their understanding of MongoDB and document databases. Resource Type Resource R eason for Recommendation Official Documentation MongoDB Documentation - Development Covers connection, CRUD, indexes, data modelling and aggregation. Official Documentation MongoDB Database Manual - Documents Explains BSON documents, fields and document structure. Official Documentation Install MongoDB Community Edition Provides current OS - specific installation instructions. Official Tool MongoDB Shell Documentation Useful for practicing commands interactively. Official Tool MongoDB Compass Graphical way to explore documents and run queries. Online Practice MongoDB University / MongoDB Learn Free guided courses and exercises for beginners. Book / Concept NoSQL Distilled by Pramod J. Sadalage and Martin Fowler Useful for understanding NoSQL database design choices. Suggested Practical Work Create a collegeDB database with students, courses and departments collections. Insert at least 20 documents, perform CRUD operations, create indexes on department and semester, and build an aggregation report sho wing average marks by department. 2.6 Assessment Questions Part A - Multiple Choice Questions (1 Mark Each) Q1. Which data format is MongoDB documents most closely related to? 1. SQL table 2. JSON - like document 3. Spreadsheet cell 4. Binary image Answer: (b) Chapter 2: Document Databases using MongoDB Unit II - NoSQL Databases Q2. What is the basic unit of data storage in MongoDB? 1. Row 2. Column 3. Document 4. Worksheet Answer: (c) Q3. Which command switches to a database in mongosh? 1. go collegeDB 2. use collegeDB 3. open c ollegeDB 4. select collegeDB Answer: (b) Q4. Which method inserts one document into a collection? 1. insertOne() 2. addRow() 3. createTable() 4. pushDoc() Answer: (a) Q5. Which method is used to read multiple documents? 1. scan() 2. fi nd() 3. selectAll() 4. readMany() Answer: (b) Q6. Which operator is commonly used to update a field value? 1. $set 2. $read 3. $table 4. $row Answer: (a) Q7. Which structure improves query performance? 1. Index 2. Footer 3. Cursor name only 4. Comment Answer: (a) Chapter 2: Document Databases using MongoDB Unit II - NoSQL Databases Q8. Which aggregation stage is used for grouping documents? 1. $sort 2. $match 3. $group 4. $limit Answer: (c) Part B - Short Answer Questions (5 Marks Each) Q9. Define a document database. How is it different from a relational database? Q10. Explain database, collection and document in MongoDB with an example. Q11. What is BSON? Why does MongoDB use BSON documents? Q12. List and explain any five core features of document databases. Q13. Write th e steps to install and verify MongoDB in a beginner lab environment. Q14. Explain the purpose of MongoDB connection strings with examples. Q15. Write mongosh commands to create a database, insert one student document and read it back. Q16. Differentiate be tween insertOne() and insertMany(). Q17. Explain updateOne(), updateMany(), deleteOne() and deleteMany() with examples. Q18. What is projection in MongoDB queries? Give one example. Q19. Explain embedding and referencing in MongoDB data modelling. Q20. What is an index? Why should unnecessary indexes be avoided? Part C - Long Answer / Essay Questions (10 Marks Each) Q21. Explain the document database paradigm in detail. Include document structure, flexible schema, nested documents, arrays and common use cases. Q22. Describe MongoDB environment setup for beginners. Include installation options, MongoDB Community Edition, Atlas, Compass, mongosh and connection strings. Q23. Explain CRUD operations in MongoDB with suitable mongosh syntax and examples for a s tudents collection. Q24. Discuss MongoDB data modelling principles. Explain embedding versus referencing with advantages and limitations. Q25. Explain indexing strategies in MongoDB. Include single - field, compound, multikey, text and unique indexes with co mmands. Q26. Describe the MongoDB aggregation framework. Explain $match, $project, $group, $sort, $limit and $unwind with examples. Part D - Analytical / Case - Based Questions Q27 (Case Study). A college wants to store student profiles, addresses, skills an d semester marks. Design a MongoDB document structure and justify which fields should be embedded. Q28 (Analyse). A query db.students.find({ department: "CSE", semester: 5 }) is slow on a large collection. Suggest a suitable index and explain why it helps. Q29 (Practical Design). Write a complete mongosh session to create a database, insert five student documents, update one record, delete one record and display all remaining records. Chapter 2: Document Databases using MongoDB Unit II - NoSQL Databases Q30 (Aggregation). Design an aggregation pipeline to calculate average Py thon marks department - wise and sort the result in descending order. Q31 (Data Modelling). An e - commerce website stores products and thousands of reviews. Explain whether reviews should be embedded or referenced, and justify your answer. References Used for This Chapter MongoDB Documentation: Development section, including documents, CRUD operations, indexes, data modeling and aggregation operations. MongoDB Database Manual: Documents and BSON document structure. MongoDB Database Manual: Connection strings a nd cluster connection methods. MongoDB Database Manual: Install MongoDB Community Edition. MongoDB Database Manual: Index types and aggregation pipeline concepts. Sadalage, P. J., and Fowler, M. NoSQL Distilled: A Brief Guide to the Emerging World of Polyg lot Persistence. End of Chapter