Home >Database >MongoDB >How do I create, read, update, and delete (CRUD) documents in MongoDB?

How do I create, read, update, and delete (CRUD) documents in MongoDB?

Karen Carpenter
Karen CarpenterOriginal
2025-03-11 18:04:17728browse

This article details performing Create, Read, Update, and Delete (CRUD) operations in MongoDB. It covers using methods like insertOne(), find(), updateOne(), deleteOne(), and best practices for efficient operations including indexing, batch operatio

How do I create, read, update, and delete (CRUD) documents in MongoDB?

How to Perform CRUD Operations in MongoDB

This section details how to perform Create, Read, Update, and Delete (CRUD) operations in MongoDB. We'll use the example of a collection named "products" with documents containing _id, name, price, and description fields.

Creating Documents: To create a new document (insert), you use the insertOne() method (for a single document) or insertMany() (for multiple documents). Here's an example using the MongoDB shell:

<code class="javascript">db.products.insertOne( { name: "Laptop", price: 1200, description: "Powerful laptop" } )
db.products.insertMany( [
  { name: "Tablet", price: 300, description: "Android tablet" },
  { name: "Keyboard", price: 75, description: "Mechanical keyboard" }
] )</code>

This code inserts one laptop document and then inserts multiple documents (tablet and keyboard) in a single operation. The _id field is automatically generated if not provided. Driver-specific implementations will be similar, using the respective driver's insertOne() or insertMany() methods.

Reading Documents: Reading documents involves querying the collection using find(). You can specify filters to retrieve specific documents. For example:

<code class="javascript">// Find all products
db.products.find()

// Find products with price less than 500
db.products.find( { price: { $lt: 500 } } )

// Find a single product by its ID
db.products.findOne( { _id: ObjectId("...") } ) // Replace ... with the actual ObjectId</code>

find() returns a cursor, allowing you to iterate through the results. findOne() returns a single document matching the query. Again, driver implementations will have equivalent methods.

Updating Documents: MongoDB provides several ways to update documents. updateOne() updates a single document, while updateMany() updates multiple documents. You use the $set operator to modify fields.

<code class="javascript">// Update the price of a specific product
db.products.updateOne( { name: "Laptop" }, { $set: { price: 1300 } } )

// Increase the price of all products by 10%
db.products.updateMany( {}, { $inc: { price: { $multiply: [ 0.1, "$price" ] } } } )</code>

The first example updates the price of a laptop. The second example uses the $inc operator to increment the price of all products. More complex updates can be achieved using other update operators like $push, $pull, $addToSet, etc.

Deleting Documents: deleteOne() removes a single document, and deleteMany() removes multiple documents.

<code class="javascript">// Delete a specific product
db.products.deleteOne( { name: "Keyboard" } )

// Delete all products with price greater than 1000
db.products.deleteMany( { price: { $gt: 1000 } } )</code>

These commands remove documents based on the provided criteria.

Best Practices for Efficient CRUD Operations in MongoDB

Efficient CRUD operations require careful consideration of several factors:

  • Indexing: Create indexes on frequently queried fields to speed up find() operations. Indexes are similar to indices in relational databases. Choose appropriate index types (e.g., single-field, compound, geospatial) based on your queries.
  • Batch Operations: Use insertMany(), updateMany(), and deleteMany() to perform operations on multiple documents in a single batch, significantly improving performance compared to individual operations.
  • Data Modeling: Design your data model carefully to minimize the number of queries needed for common operations. Proper schema design can dramatically improve query performance.
  • Query Optimization: Avoid using $where clauses as they can be slow. Instead, use operators like $gt, $lt, $in, etc., which leverage indexes effectively. Use appropriate projection ({ _id: 0, name: 1, price: 1 }) to retrieve only the necessary fields, reducing data transfer.
  • Connection Pooling: Use connection pooling to reuse database connections, reducing the overhead of establishing new connections for each operation. Most drivers offer built-in connection pooling capabilities.

Handling Errors During CRUD Operations

Error handling is crucial for robust MongoDB applications. Drivers provide mechanisms to catch and handle exceptions during CRUD operations.

  • Try-Catch Blocks: Wrap your CRUD operations within try-catch blocks to handle potential errors like network issues, invalid data, or database errors.
  • Error Codes: Examine the error codes returned by the database to determine the cause of the error and implement appropriate logic to handle it gracefully. MongoDB provides detailed error code documentation.
  • Logging: Log errors for debugging and monitoring purposes. Include relevant information such as the error message, stack trace, and the operation that failed.
  • Retry Mechanism: Implement a retry mechanism for transient errors (e.g., network timeouts). Retry a failed operation after a short delay to improve resilience.

Performing CRUD Operations with Different Drivers

The specific methods for performing CRUD operations vary slightly depending on the driver used. Here's a brief overview for Node.js and Python:

Node.js (using the mongodb driver):

<code class="javascript">const { MongoClient } = require('mongodb');

// ... connection code ...

const client = new MongoClient(uri);

async function run() {
  try {
    await client.connect();
    const db = client.db('mydatabase');
    const collection = db.collection('products');

    // ... CRUD operations using collection.insertOne(), collection.find(), etc. ...
  } finally {
    await client.close();
  }
}
run().catch(console.dir);</code>

Python (using the pymongo driver):

<code class="python">import pymongo

# ... connection code ...

client = pymongo.MongoClient(uri)
db = client['mydatabase']
collection = db['products']

# ... CRUD operations using collection.insert_one(), collection.find(), etc. ...

client.close()</code>

Both examples demonstrate the basic structure. Consult the documentation for your specific driver for detailed information on the available methods and options. Remember to replace placeholders like uri with your actual connection string.

The above is the detailed content of How do I create, read, update, and delete (CRUD) documents in MongoDB?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn