Skip to content

Chapter 2 of 8

CRUD Operations and Querying

MongoDB provides a comprehensive set of CRUD, or Create, Read, Update, Delete, operations that map cleanly onto everyday application needs. To create documents, you use db.collection.insertOne() for a single record or db.collection.insertMany() for multiple records. MongoDB automatically assigns an _id to each document if one is not supplied, freeing developers from manually managing unique identifiers.

Reading data is handled through db.collection.find(), which accepts a filter and an optional projection. For example, db.users.find({ age: { $gt: 25 } }) returns all users older than 25, while findOne() returns only the first matching document. To refine queries, MongoDB offers a rich set of operators. Comparison operators like $eq, $ne, $gt, $gte, $lt, $lte, $in, and $nin filter by value relationships, while logical operators such as $and, $or, $not, and $nor combine conditions. Element operators like $exists and $type check for the presence or type of fields, and array operators including $all, $elemMatch, and $size target array contents.

Updating documents is accomplished with updateOne(), updateMany(), or replaceOne(). These accept update operators that precisely describe how to modify fields: $set assigns a new value and creates the field if it does not exist, $unset removes a field, $inc increments a numeric value, $push appends to an array, and $pull removes elements from an array. The $set operator can also target nested fields using dot notation, such as "address.city". To prevent duplicates when adding to arrays, $addToSet inserts a value only if it does not already exist in the array, and combining it with $each allows multiple unique values to be added at once. Deleting documents follows the same pattern with deleteOne() and deleteMany().

All chapters
  1. 1Foundations of MongoDB
  2. 2CRUD Operations and Querying
  3. 3The Aggregation Framework
  4. 4Indexing and Query Performance
  5. 5Replication for High Availability
  6. 6Sharding for Horizontal Scaling
  7. 7Schema Design Patterns
  8. 8Advanced Features and Ecosystem

Drill it

Reading is not remembering. These come from the Nosql MongoDB deck:

Q

What is MongoDB?

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...

Q

What is the document model in MongoDB?

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-do...

Q

What is BSON?

BSON (Binary JSON) is the binary-encoded serialization format MongoDB uses to store documents and make remote procedure calls. It extends JSON with additional d...

Q

What is an ObjectId in MongoDB?

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 timestampA 5-...