Unit 5: MongoDB Integration - Practice Quiz

CSE494 — Intelligent Nosql Databases 60 Questions
0 Correct 0 Wrong 60 Left
0/60

1 What is Mongoose in a Node.js application?

MongoDB Integration with Node.js using Mongoose Easy
A. A Python database driver
B. A JavaScript ODM for MongoDB
C. A MongoDB backup utility
D. A database server monitor

2 Which object is commonly used to define the structure of documents in Mongoose?

MongoDB Integration with Node.js using Mongoose Easy
A. Express Router
B. MongoDB Cursor
C. Mongoose Schema
D. Node.js Buffer

3 Which method is commonly used to connect Mongoose to MongoDB?

MongoDB Integration with Node.js using Mongoose Easy
A. mongoose.startServer()
B. mongoose.connect()
C. mongoose.createTable()
D. mongoose.openFile()

4 What does a Mongoose model represent?

MongoDB Integration with Node.js using Mongoose Easy
A. A server log file
B. A collection interface
C. A network address
D. A database password

5 What is PyMongo?

MongoDB Integration with Python using PyMongo Easy
A. A Python web server
B. A JavaScript schema library
C. A Python driver for MongoDB
D. A MongoDB visualization tool

6 Which PyMongo class is commonly used to create a connection to MongoDB?

MongoDB Integration with Python using PyMongo Easy
A. MongoSession
B. MongoDatabase
C. MongoConnector
D. MongoClient

7 In PyMongo, what does a collection store?

MongoDB Integration with Python using PyMongo Easy
A. Application source files
B. Related documents
C. Only SQL statements
D. Only database users

8 Which PyMongo method retrieves a single document?

MongoDB Integration with Python using PyMongo Easy
A. get_single()
B. select_one()
C. find_one()
D. read_document()

9 What does the letter C represent in CRUD?

CRUD using Application Code Easy
A. Connect
B. Compile
C. Create
D. Calculate

10 Which CRUD operation is used to retrieve documents from MongoDB?

CRUD using Application Code Easy
A. Delete
B. Update
C. Create
D. Read

11 Which MongoDB method inserts one document into a collection?

CRUD using Application Code Easy
A. insertOne()
B. addRecord()
C. saveSingle()
D. createRow()

12 Which MongoDB method updates one matching document?

CRUD using Application Code Easy
A. changeOne()
B. modifySingle()
C. editRecord()
D. updateOne()

13 Which MongoDB method removes one matching document?

CRUD using Application Code Easy
A. removeRecord()
B. dropDocument()
C. deleteOne()
D. eraseSingle()

14 What is predictive analytics used for?

MongoDB for AI-based Predictive Analytics Easy
A. Deleting old databases
B. Changing network cables
C. Forecasting future outcomes
D. Formatting source code

15 How can MongoDB support predictive analytics?

MongoDB for AI-based Predictive Analytics Easy
A. By preventing data collection
B. By converting documents to webpages
C. By storing model input data
D. By replacing every AI model

16 Which type of data can MongoDB store for an AI prediction system?

MongoDB for AI-based Predictive Analytics Easy
A. Only printed documents
B. Only database passwords
C. Only programming comments
D. Historical customer activity

17 What is a common purpose of using AI with MongoDB data?

MongoDB for AI-based Predictive Analytics Easy
A. Removing all document fields
B. Replacing application interfaces
C. Finding patterns in data
D. Disabling database queries

18 What is the main goal of query optimization?

AI-driven Query Optimization in NoSQL Databases Easy
A. Improve query performance
B. Increase duplicate documents
C. Change documents into tables
D. Remove database indexes

19 What can an index help MongoDB do?

AI-driven Query Optimization in NoSQL Databases Easy
A. Find matching data faster
B. Store application passwords
C. Replace all database documents
D. Create user interface screens

20 What may AI analyze to recommend better database queries?

AI-driven Query Optimization in NoSQL Databases Easy
A. Source code indentation
B. Query execution patterns
C. Screen color preferences
D. User profile pictures

21 A Mongoose application only needs to read user records and return plain JSON objects. The records will not be modified or saved. Which query is most appropriate for reducing Mongoose document-processing overhead?

MongoDB Integration with Node.js using Mongoose Medium
A. User.find({ active: true }).populate()
B. User.find({ active: true }).hydrate()
C. User.find({ active: true }).validate()
D. User.find({ active: true }).lean()

22 A developer updates a product with Product.findByIdAndUpdate(id, update). The returned value contains the product data from before the update. Which option should be added to return the updated document?

MongoDB Integration with Node.js using Mongoose Medium
A. { strict: true }
B. { new: true }
C. { upsert: true }
D. { lean: true }

23 A Mongoose schema requires price to be at least 1. An update using findOneAndUpdate() incorrectly accepts price: 0. Which option should be included in the update operation?

MongoDB Integration with Node.js using Mongoose Medium
A. { minimize: true }
B. { autoIndex: true }
C. { runValidators: true }
D. { timestamps: true }

24 An order-creation endpoint must insert an order and decrease product stock as one atomic operation. What is the most appropriate Mongoose approach?

MongoDB Integration with Node.js using Mongoose Medium
A. Execute both operations with separate model hooks
B. Execute both operations in a transaction session
C. Execute both operations with parallel read queries
D. Execute both operations through virtual properties

25 A Flask route receives a MongoDB document ID as a URL string. Which conversion is normally required before using it in a PyMongo _id query?

MongoDB Integration with Python using PyMongo Medium
A. ObjectId(id_string)
B. bytes(id_string)
C. UUID(id_string)
D. str(id_string)

26 A Python service must retrieve only the name and score fields while excluding _id. Which PyMongo query uses the correct projection?

MongoDB Integration with Python using PyMongo Medium
A. find({}, {"name": 0, "score": 0, "_id": 1})
B. find({"_id": 0}, {"name": 1, "score": 1})
C. find({}, {"name": 1, "score": 1, "_id": 0})
D. find({"name": 1, "score": 1}, {"_id": 0})

27 A PyMongo application frequently creates a new MongoClient for every request and closes it immediately afterward. What is the preferred design for a typical web service?

MongoDB Integration with Python using PyMongo Medium
A. Create one MongoClient for each collection operation
B. Reuse one long-lived MongoClient across requests
C. Create one MongoClient for each returned document
D. Reuse one cursor permanently across all requests

28 A data-loading job has 5,000 independent update operations to send through PyMongo. Which approach generally reduces network round trips while allowing the operations to be grouped?

MongoDB Integration with Python using PyMongo Medium
A. Use find_one() before every update
B. Use aggregate() with output projections
C. Use watch() with update filters
D. Use bulk_write() with update models

29 An inventory API must reduce stock by 1 only when the current stock is greater than 0. Which update best prevents two concurrent requests from overselling the final item?

CRUD using Application Code Medium
A. Filter only on the product ID and apply $set: { stock: 0 }
B. Read the stock twice and later apply $inc: { stock: -1 }
C. Read the stock first and later apply $set: { stock: stock - 1 }
D. Filter on stock: { $gt: 0 } and apply $inc: { stock: -1 }

30 A REST API calls delete_one({"_id": id}) and receives deleted_count == 0. Which HTTP response is most appropriate when the identifier was valid but no matching resource existed?

CRUD using Application Code Medium
A. 409 Conflict
B. 404 Not Found
C. 201 Created
D. 304 Not Modified

31 A profile update endpoint receives only { "city": "Pune" }. The existing name and email fields must remain unchanged. Which update document should the application construct?

CRUD using Application Code Medium
A. { "$set": { "city": "Pune" } }
B. { "$replaceWith": { "city": "Pune" } }
C. { "$unset": { "city": "Pune" } }
D. { "$rename": { "city": "Pune" } }

32 Two users can edit the same document. The document contains a numeric version field. How should the application implement optimistic concurrency control?

CRUD using Application Code Medium
A. Match _id and a new version, then decrement version
B. Match version only, then replace every field in the document
C. Match _id and the expected version, then increment version
D. Match _id only, then reset version to its initial value

33 A predictive-maintenance model needs each machine's average temperature during the previous hour. Where can this feature be efficiently computed before model inference?

MongoDB for AI-based Predictive Analytics Medium
A. In a unique index using field ordering and collation
B. In an aggregation pipeline using time filtering and grouping
C. In a transaction using write concern and retry settings
D. In a schema validator using required fields and types

34 A model predicts whether a customer will cancel a subscription tomorrow. Which feature would cause target leakage during training?

MongoDB for AI-based Predictive Analytics Medium
A. The customer's payment failures before prediction time
B. The customer's subscription duration at prediction time
C. A cancellation confirmation recorded after the prediction time
D. The number of support requests submitted last month

35 An application stores model predictions with modelVersion, predictedAt, and featuresVersion. What is the main analytical benefit of storing this metadata?

MongoDB for AI-based Predictive Analytics Medium
A. Predictions can be traced and compared across model versions
B. Documents automatically migrate to the newest feature schema
C. Queries automatically avoid scanning historical prediction data
D. Predictions automatically become accurate after model retraining

36 A deployed fraud model should score new transactions shortly after they are inserted into MongoDB. Which MongoDB capability is most suitable for triggering this near-real-time workflow?

MongoDB for AI-based Predictive Analytics Medium
A. Change streams on the transactions collection
B. Schema validation on the transaction amount
C. Text indexes on the transaction description
D. Read preferences on the transaction database

37 An AI optimizer observes the frequent query find({ tenantId: T, status: S }).sort({ createdAt: -1 }). Which compound index is the strongest candidate?

AI-driven Query Optimization in NoSQL Databases Medium
A. { tenantId: 1, status: 1, createdAt: -1 }
B. { createdAt: -1, tenantId: 1, status: 1 }
C. { tenantId: -1, createdAt: 1, status: -1 }
D. { status: 1, createdAt: 1, tenantId: -1 }

38 After an AI system recommends an index, which explain() evidence most strongly indicates that the query became more efficient?

AI-driven Query Optimization in NoSQL Databases Medium
A. More execution stages with the same scan volume
B. More documents examined for the same number returned
C. A larger index with the same collection scan
D. Fewer documents examined for the same number returned

39 An optimizer proposes indexes for every observed query pattern, but the collection has heavy write traffic. Which factor should prevent automatic acceptance of all recommendations?

AI-driven Query Optimization in NoSQL Databases Medium
A. Each additional index removes fields from query projections
B. Each additional index increases write and storage overhead
C. Each additional index forces queries to use collection scans
D. Each additional index disables document-level atomic updates

40 Query traffic changes substantially between business hours and overnight batch processing. What input would best help an AI optimizer adapt its recommendations?

AI-driven Query Optimization in NoSQL Databases Medium
A. Recent query shapes, frequencies, latencies, and execution statistics
B. Only collection names, database names, and server hostnames
C. Only schema field names, BSON types, and validation messages
D. Only application versions, deployment dates, and source branches

41 A Mongoose schema defines email with unique: true. Two concurrent requests create documents with the same email, and both validations pass before either write completes. What is the reliable way to enforce uniqueness?

MongoDB Integration with Node.js using Mongoose Hard
A. Set required: true on the email field
B. Rely on Mongoose validation during save()
C. Use findOne() before every insert
D. Add a unique index and handle duplicate-key errors

42 A Mongoose update uses Model.updateOne({ _id: id }, { $set: payload }), where payload is received from an API client. Which design best prevents unauthorized field changes and operator injection?

MongoDB Integration with Node.js using Mongoose Hard
A. Pass the entire payload to $set after checking authentication
B. Convert every payload value to a string before updating
C. Use strict: false so Mongoose preserves client fields
D. Allow only a server-defined field allowlist and reject keys beginning with $

43 A service uses findOneAndUpdate() to increment an account balance and expects the returned document to contain the new balance. Which configuration is required for that expectation?

MongoDB Integration with Node.js using Mongoose Hard
A. new: true
B. timestamps: false
C. lean: true
D. overwrite: true

44 A Mongoose query uses populate('customer') and returns thousands of orders. The customer documents contain large profile fields that the API never exposes. Which change most directly reduces response size and hydration cost?

MongoDB Integration with Node.js using Mongoose Hard
A. Replace populate() with estimatedDocumentCount()
B. Set strictPopulate to false
C. Call populate('customer') twice
D. Use populate('customer', 'name tier')

45 A PyMongo application must transfer a newly inserted document's identifier to another collection, and both writes must commit atomically. Which approach is appropriate when the deployment supports transactions?

MongoDB Integration with Python using PyMongo Hard
A. Execute both writes with separate client calls
B. Use a session and with_transaction()
C. Use insert_many() on unrelated collections
D. Call acknowledged=False for lower latency

46 A PyMongo worker retries a transaction after a transient network error. The transaction inserts a document with a client-generated UUID and a unique index on that UUID. Why is this design useful?

MongoDB Integration with Python using PyMongo Hard
A. It removes the need for write concern
B. It makes retried logical inserts idempotent
C. It guarantees reads never use stale data
D. It disables transaction write conflicts

47 A PyMongo query sorts by event_time descending and limits results, but performance degrades as the collection grows. The filter is { "tenant_id": t, "status": "open" }. Which index is generally the strongest candidate?

MongoDB Integration with Python using PyMongo Hard
A. { tenant_id: 1, status: 1, event_time: -1 }
B. { status: 1, event_time: -1 }
C. { event_time: -1 }
D. { tenant_id: 1, event_time: -1 }

48 A Python API reads documents using find() and converts them to JSON. Some documents contain ObjectId and timezone-aware datetime values. What is the most robust boundary design?

MongoDB Integration with Python using PyMongo Hard
A. Store identifiers and dates only as binary values
B. Convert every value to an arbitrary string
C. Use BSON-aware serialization such as Extended JSON
D. Disable BSON decoding in the MongoClient

49 An order update must change status from pending to paid only if it is still pending, and the application must know whether the transition occurred. Which operation is most suitable?

CRUD using Application Code Hard
A. Delete the order and insert a paid replacement
B. Update with _id and status: "pending", then inspect matched_count
C. Update by _id only and inspect the modified document
D. Read the order, modify it locally, and replace it unconditionally

50 An application performs pagination with skip(page * 100).limit(100) on a collection receiving continuous inserts. Which issue is most likely, and what is the better strategy for a large collection?

CRUD using Application Code Hard
A. Limit causes duplicate writes; use bulk deletion
B. Sorting is always implicit; remove the sort clause
C. Skip prevents all index usage; use random sampling
D. Inserts can shift pages; use a stable range cursor

51 A delete endpoint receives a user-supplied filter and passes it directly to deleteMany(). Which control is most important for preventing accidental broad deletion?

CRUD using Application Code Hard
A. Use deleteMany() instead of deleteOne()
B. Disable acknowledged writes
C. Require a nonempty filter and enforce an allowlisted predicate
D. Set the collection's capped size

52 A bulk import contains 10,000 independent records. Some records violate a unique index, but valid records should still be inserted. Which behavior best matches this requirement?

CRUD using Application Code Hard
A. Use replaceOne() without an upsert option
B. Use ordered bulk writes and abort on the first error
C. Use a transaction that ignores all duplicate errors
D. Use unordered bulk writes and inspect individual write errors

53 A read-modify-write workflow increments a counter, but concurrent requests occasionally overwrite each other's increments. Which database-side change is the best fix?

CRUD using Application Code Hard
A. Use $inc in a single atomic update
B. Add a random delay before each write
C. Serialize requests only in the web process
D. Read the document twice before writing

54 A predictive model estimates customer churn from historical customer snapshots. The feature pipeline includes each customer's last_support_ticket, but the ticket may have been created after the prediction timestamp. What problem does this create?

MongoDB for AI-based Predictive Analytics Hard
A. High-cardinality indexing
B. BSON serialization drift
C. Write concern starvation
D. Target leakage from future information

55 A feature-generation aggregation joins transactions to accounts and then groups by account. The transaction collection is much larger, and only transactions from the previous 30 days are relevant. Where should the time filter normally be applied?

MongoDB for AI-based Predictive Analytics Hard
A. Inside the transaction-side $match before the join
B. Only after exporting data to Python
C. In a projection after the model receives the features
D. After the final grouping

56 A production model uses a feature that is computed from documents arriving through a change stream. Events can arrive out of order. Which design best preserves correct time-window features?

MongoDB for AI-based Predictive Analytics Hard
A. Sort only by MongoDB insertion order
B. Use event-time watermarks and recompute affected windows
C. Discard all events that arrive after the first batch
D. Assume arrival order equals event-time order

57 A team evaluates a fraud model by randomly splitting transactions into training and test sets. Fraud patterns evolve over time, and the model will score future transactions. Which evaluation design is more defensible?

MongoDB for AI-based Predictive Analytics Hard
A. Evaluate only on the training aggregation
B. Use a chronological split with leakage checks
C. Randomly oversample the test set
D. Shuffle labels before calculating accuracy

58 An optimizer recommends an index { status: 1, region: 1 } for a workload, but the query filters on region and sorts by created_at while omitting status. Why may the recommendation be ineffective?

AI-driven Query Optimization in NoSQL Databases Hard
A. Indexes cannot contain strings
B. Sorting cannot use compound indexes
C. The leading index field is not constrained
D. MongoDB ignores every index with two fields

59 An AI query tuner reports that a query's average latency improved after adding an index, but p99 latency and write throughput both worsened. What is the best conclusion?

AI-driven Query Optimization in NoSQL Databases Hard
A. The index is universally beneficial
B. Write throughput is unrelated to index count
C. The index should be evaluated against tail latency and write cost
D. Average latency proves the query plan is stable

60 A learned optimizer detects that a query is slow because a predicate has highly skewed values. It proposes different plans for frequent and rare values. What capability is this exploiting?

AI-driven Query Optimization in NoSQL Databases Hard
A. Client-side result caching
B. Parameter-sensitive plan selection
C. Schema-free serialization
D. Automatic document normalization