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 JavaScript ODM for MongoDB
B. A Python database driver
C. A database server monitor
D. A MongoDB backup utility

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

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

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

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

4 What does a Mongoose model represent?

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

5 What is PyMongo?

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

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

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

7 In PyMongo, what does a collection store?

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

8 Which PyMongo method retrieves a single document?

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

9 What does the letter C represent in CRUD?

CRUD using Application Code Easy
A. Create
B. Compile
C. Connect
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. saveSingle()
B. createRow()
C. addRecord()
D. insertOne()

12 Which MongoDB method updates one matching document?

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

13 Which MongoDB method removes one matching document?

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

14 What is predictive analytics used for?

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

15 How can MongoDB support predictive analytics?

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

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

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

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

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

18 What is the main goal of query optimization?

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

19 What can an index help MongoDB do?

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

20 What may AI analyze to recommend better database queries?

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

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 }).hydrate()
B. User.find({ active: true }).validate()
C. User.find({ active: true }).lean()
D. User.find({ active: true }).populate()

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. { lean: true }
B. { new: true }
C. { upsert: true }
D. { strict: 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. { runValidators: true }
B. { timestamps: true }
C. { minimize: true }
D. { autoIndex: 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 in a transaction session
B. Execute both operations with parallel read queries
C. Execute both operations with separate model hooks
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. UUID(id_string)
B. bytes(id_string)
C. str(id_string)
D. ObjectId(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": 1, "score": 1, "_id": 0})
B. find({"_id": 0}, {"name": 1, "score": 1})
C. find({}, {"name": 0, "score": 0, "_id": 1})
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 returned document
B. Reuse one cursor permanently across all requests
C. Create one MongoClient for each collection operation
D. Reuse one long-lived MongoClient across 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 aggregate() with output projections
B. Use bulk_write() with update models
C. Use find_one() before every update
D. Use watch() with update filters

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. Read the stock first and later apply $set: { stock: stock - 1 }
B. Read the stock twice and later apply $inc: { stock: -1 }
C. Filter only on the product ID and apply $set: { stock: 0 }
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. 201 Created
B. 304 Not Modified
C. 409 Conflict
D. 404 Not Found

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 only, then reset version to its initial value
B. Match _id and the expected version, then increment version
C. Match _id and a new version, then decrement version
D. Match version only, then replace every field in the document

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 an aggregation pipeline using time filtering and grouping
B. In a transaction using write concern and retry settings
C. In a unique index using field ordering and collation
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. A cancellation confirmation recorded after the prediction time
B. The number of support requests submitted last month
C. The customer's subscription duration at prediction time
D. The customer's payment failures before prediction time

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. Queries automatically avoid scanning historical prediction data
B. Documents automatically migrate to the newest feature schema
C. Predictions automatically become accurate after model retraining
D. Predictions can be traced and compared across model versions

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. Read preferences on the transaction database
B. Text indexes on the transaction description
C. Change streams on the transactions collection
D. Schema validation on the transaction amount

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. { createdAt: -1, tenantId: 1, status: 1 }
B. { tenantId: 1, status: 1, createdAt: -1 }
C. { status: 1, createdAt: 1, tenantId: -1 }
D. { tenantId: -1, createdAt: 1, status: -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. Fewer documents examined for the same number returned
B. More execution stages with the same scan volume
C. More documents examined for the same number returned
D. A larger index with the same collection scan

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 increases write and storage overhead
B. Each additional index disables document-level atomic updates
C. Each additional index removes fields from query projections
D. Each additional index forces queries to use collection scans

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. Only collection names, database names, and server hostnames
B. Only application versions, deployment dates, and source branches
C. Only schema field names, BSON types, and validation messages
D. Recent query shapes, frequencies, latencies, and execution statistics

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. Rely on Mongoose validation during save()
B. Add a unique index and handle duplicate-key errors
C. Set required: true on the email field
D. Use findOne() before every insert

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. Convert every payload value to a string before updating
B. Use strict: false so Mongoose preserves client fields
C. Pass the entire payload to $set after checking authentication
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. overwrite: true
B. lean: true
C. new: true
D. timestamps: false

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. Call populate('customer') twice
B. Use populate('customer', 'name tier')
C. Replace populate() with estimatedDocumentCount()
D. Set strictPopulate to false

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. Call acknowledged=False for lower latency
B. Use insert_many() on unrelated collections
C. Use a session and with_transaction()
D. Execute both writes with separate client calls

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 disables transaction write conflicts
B. It removes the need for write concern
C. It makes retried logical inserts idempotent
D. It guarantees reads never use stale data

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, event_time: -1 }
B. { tenant_id: 1, status: 1, event_time: -1 }
C. { event_time: -1 }
D. { status: 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. Use BSON-aware serialization such as Extended JSON
B. Disable BSON decoding in the MongoClient
C. Convert every value to an arbitrary string
D. Store identifiers and dates only as binary values

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. Update by _id only and inspect the modified document
B. Read the order, modify it locally, and replace it unconditionally
C. Delete the order and insert a paid replacement
D. Update with _id and status: "pending", then inspect matched_count

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. Skip prevents all index usage; use random sampling
B. Inserts can shift pages; use a stable range cursor
C. Limit causes duplicate writes; use bulk deletion
D. Sorting is always implicit; remove the sort clause

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. Require a nonempty filter and enforce an allowlisted predicate
B. Use deleteMany() instead of deleteOne()
C. Set the collection's capped size
D. Disable acknowledged writes

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 unordered bulk writes and inspect individual write errors
B. Use a transaction that ignores all duplicate errors
C. Use replaceOne() without an upsert option
D. Use ordered bulk writes and abort on the first error

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. Add a random delay before each write
B. Use $inc in a single atomic update
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. Target leakage from future information
B. Write concern starvation
C. High-cardinality indexing
D. BSON serialization drift

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. In a projection after the model receives the features
C. Only after exporting data to Python
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. Discard all events that arrive after the first batch
B. Assume arrival order equals event-time order
C. Sort only by MongoDB insertion order
D. Use event-time watermarks and recompute affected windows

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. Shuffle labels before calculating accuracy
B. Evaluate only on the training aggregation
C. Use a chronological split with leakage checks
D. Randomly oversample the test set

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. MongoDB ignores every index with two fields
B. Sorting cannot use compound indexes
C. The leading index field is not constrained
D. Indexes cannot contain strings

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. Write throughput is unrelated to index count
B. Average latency proves the query plan is stable
C. The index should be evaluated against tail latency and write cost
D. The index is universally beneficial

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. Automatic document normalization
C. Parameter-sensitive plan selection
D. Schema-free serialization