Master MongoDB CRUD Operations: 4 Essential Basic Operations for Beginners

Prerequisites: MongoDB Basics

Before starting to learn CRUD operations, let’s briefly understand MongoDB’s characteristics: it is a document - oriented database, where data is stored in JSON - like format (BSON). It has no fixed table structure. Each data unit is called a “document”, and these documents are stored in “collections”.

Pre - operation Setup:
1. Start the MongoDB service (no additional configuration is needed for local default). Enter mongo in the command line to access the Mongo Shell.
2. Switch to the target database (e.g., use mydb; if it does not exist, it will be automatically created).
3. Select the collection to operate on (e.g., db.users; if it does not exist, it will be automatically created when data is inserted).

1. Create (Insert): Add Data to Collections

The core of the create operation is to add new documents to the collection. The commonly used methods are:

1.1 Insert a Single Document: insertOne()

Syntax: db.collection_name.insertOne(document_object)

Example: Insert a user information into the users collection:

// Insert a single document
db.users.insertOne({
  name: "Zhang San",
  age: 20,
  email: "zhangsan@example.com"
})

Return Result:

{
  "acknowledged": true,  // Operation confirmation
  "insertedId": "650a0b12c3d4e5f6a7b8c9d0",  // Automatically generated unique ID (_id)
  "insertedCount": 1
}

1.2 Insert Multiple Documents: insertMany()

Syntax: db.collection_name.insertMany([document1, document2, ...])

Example: Insert two user data:

db.users.insertMany([
  { name: "Li Si", age: 22, email: "lisi@example.com" },
  { name: "Wang Wu", age: 21, email: "wangwu@example.com" }
])

Return Result:

{
  "acknowledged": true,
  "insertedIds": [
    "650a0b12c3d4e5f6a7b8c9d1",
    "650a0b12c3d4e5f6a7b8c9d2"
  ],
  "insertedCount": 2
}

2. Read (Query): Retrieve Data from Collections

The read operation is used to obtain data from the collection. The core is the find() method, which supports conditional filtering, field projection, sorting, and more.

2.1 Query All Documents: find()

Syntax: db.collection_name.find(query_conditions, {field_projection})

  • Query Conditions: An empty object {} means querying all documents.
  • Field Projection: {field_name: 1} means returning that field, and {field_name: 0} means excluding that field (_id is returned by default; it needs to be explicitly set to 0 to exclude it).

Example: Query all user information in the users collection and only return name and age:

// 1. Query all documents and return all fields
db.users.find()

// 2. Only return name and age (exclude _id)
db.users.find({}, { name: 1, age: 1, _id: 0 })

2.2 Conditional Query:

Conditional filtering is used to retrieve specific documents. Common operators include: equals (=), greater than (> ), less than (< ), not equal (!=), in (包含), etc.

Example: Query users with an age of 20:

db.users.find({ age: 20 })  // Condition: age = 20

Example: Query users older than 21:

db.users.find({ age: { $gt: 21 } })  // $gt means greater than

2.3 Sorting and Limiting the Number of Results:

  • Sorting: sort({field: 1}) (1 = ascending order, -1 = descending order).
  • Limiting the Number of Results: limit(n) (only return the first n results).

Example: Query users under 25 years old, sorted by age in ascending order, and only return the first 2 results:

db.users.find({ age: { $lt: 25 } })
  .sort({ age: 1 })  // Sort in ascending order
  .limit(2)          // Limit to return 2 results

3. Update (Modify): Update Collection Data

The update operation requires clearly defining the modification rules (conditions) and modification methods (operators). The commonly used methods are:

3.1 Update a Single Document: updateOne()

Syntax: db.collection_name.updateOne(query_conditions, {modification_operations})

Common Modification Operators:
- $set: Overwrite a field (e.g., modify name and age).
- $inc: Increment a field (e.g., age + 1).

Example: Increase the age of the user named “Zhang San” by 1:

db.users.updateOne(
  { name: "Zhang San" },  // Query condition: name = Zhang San
  { $inc: { age: 1 } }  // Modification operation: age is incremented by 1
)

Example: Change the name of the user named “Li Si” to “Li Hua”:

db.users.updateOne(
  { name: "Li Si" },
  { $set: { name: "Li Hua" } }  // Modify the name field
)

3.2 Update Multiple Documents: updateMany()

Syntax: db.collection_name.updateMany(query_conditions, {modification_operations})

Example: Set the age of all users under 22 to 22:

db.users.updateMany(
  { age: { $lt: 22 } },  // Condition: age < 22
  { $set: { age: 22 } }  // Overwrite the age field
)

4. Delete (Remove): Remove Collection Data

Be cautious with delete operations to avoid accidental data loss. The commonly used methods are:

4.1 Delete a Single Document: deleteOne()

Syntax: db.collection_name.deleteOne(query_conditions)

Example: Delete the user named “Wang Wu”:

db.users.deleteOne({ name: "Wang Wu" })

4.2 Delete Multiple Documents: deleteMany()

Syntax: db.collection_name.deleteMany(query_conditions)

Example: Delete all users over 22 years old:

db.users.deleteMany({ age: { $gt: 22 } })

4.3 Clear the Collection (Dangerous Operation!):

Delete all documents (confirm that there is no important data in the collection):

db.users.deleteMany({})  // An empty condition means deleting all documents

Summary

MongoDB’s CRUD operations are the foundation of data management. The core points are:
- Create: Use insertOne/insertMany to insert documents.
- Read: Use find with conditions, projection, and sorting to query data.
- Update: Use updateOne/updateMany with $set/$inc and other operators to modify data.
- Delete: Use deleteOne/deleteMany with conditions to delete, and avoid accidental deletion.

Practice Suggestion: Create a new students collection and try to complete the full process: “Insert 3 student data → Query students over 18 years old → Increase the age of all 18 - year - old students by 1 → Delete all female students”. This will help you become familiar with the details of each operation.

With these basic operations, you can independently perform CRUD operations on MongoDB data. In the future, you can learn advanced functions such as indexes and aggregation pipelines!

Xiaoye