Overview

4 Executing CRUD operations

This chapter introduces how to execute the full spectrum of CRUD operations in MongoDB using mongosh, framing them as the core of a document’s lifecycle: create, read, update, and delete. It orients you to working against sample data in Atlas, shows how queries return cursors for efficient, batched retrieval, and demonstrates essential query tooling such as projections, logical and comparison operators, regex matching, and pagination with sort, skip, and limit. It also highlights platform features that shape behavior and robustness, including read-operation timeouts via defaultMaxTimeMS and long-term API compatibility through the Stable API.

On the write path, the chapter covers inserting single or multiple documents with insertOne and insertMany, discussing ordered versus unordered execution, BSON size and batch limits, and performance implications of indexing during bulk loads. It explains updating with updateOne, updateMany, and replaceOne, clarifying upserts, immutable _id behavior, and why targeted field updates are often more efficient than whole-document replacements. A large portion focuses on precise, atomic changes through update operators (such as set, inc, min, max, unset, currentDate) and powerful array manipulation patterns using push, addToSet, pull, pop, direct indexing, the positional operator ($), and filtered positional updates with arrayFilters for fine-grained control.

On the read and maintenance path, it shows how to compose expressive filters with logical and comparison operators, handle nulls and missing fields with exists and type, query arrays and embedded documents via dot notation or exact matches (and why exact matches are brittle), and tune results with concise projections. For result navigation and application flow, it explains cursor semantics, manual iteration, and toArray trade-offs. It closes with careful delete practices (deleteOne, deleteMany, findOneAndDelete, and pre-validating filters), bulk automation through bulkWrite, and the MongoDB 8.0 bulkWrite command that spans multiple namespaces, including guidance on ordered vs unordered trade-offs. Throughout, the chapter emphasizes guardrails and best practices: validate filters with a find first, use unique indexes for safe upserts, avoid relying on insertion order in unordered writes, and leverage Stable API pinning to prevent breaking changes across server upgrades.

Summary

  • insertOne and insertMany enable the addition of new documents to MongoDB databases.
  • Read operations include advanced query capabilities, allowing for effective data retrieval through the use of the find() method, which supports detailed query filters and options to precisely define the documents to be retrieved.
  • Update operations include the updateOne and updateMany commands, offering precise adjustments to existing documents. You can use operators such as $set, $inc, $push, and $unset, which allow for specific modifications to document fields, ranging from updating existing values to adding new elements to arrays.
  • Remove operations use the deleteOne and deleteMany methods, focusing on the secure removal of documents while preserving database integrity.
  • Arrays use operators like $push, $pop, $addToSet, and $pull to efficiently structure and modify array data within documents. This functionality is crucial for dynamic data handling and organization in MongoDB.
  • Starting in MongoDB 8.0, the bulkWrite command enables multiple insert, update, and delete operations across several collections in a single request, unlike the db.collection.bulkWrite() method that only modifies one collection per request.
  • Cursors in MongoDB streamline the process of navigating through large datasets, enabling efficient data retrieval by sequentially accessing documents one at a time.
  • The Stable API feature in MongoDB ensures compatibility across server versions and consistent API behavior.

FAQ

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • MongoDB 8.0 in Action, Third Edition ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • MongoDB 8.0 in Action, Third Edition ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • MongoDB 8.0 in Action, Third Edition ebook for free