Basic CRUD Operations in MongoDB (insertOne, find, updateOne, deleteOne)


Introduction

In this module, we will explore the basic CRUD operations in MongoDB, which are essential for interacting with data stored in a MongoDB database. CRUD stands for Create, Read, Update, and Delete, the four fundamental operations required to manage data. These operations are performed using specific methods in MongoDB, and we’ll cover how to use them for everyday database tasks.

  • insertOne: Adds a single document to a collection.
  • find: Queries documents from a collection.
  • updateOne: Updates a single document in a collection.
  • deleteOne: Deletes a single document from a collection.

1. insertOne: Creating a New Document

The insertOne method is used to add a new document to a collection in MongoDB. The document is written in BSON (Binary JSON) format and can contain any number of fields.

Syntax:

javascriptCopyEditdb.collection.insertOne(document)
  • document: A JavaScript object representing the document to be inserted.

Example:

javascriptCopyEdit// Connecting to the MongoDB instance
const { MongoClient } = require('mongodb');
const uri = "mongodb://localhost:27017"; // MongoDB URL
const client = new MongoClient(uri);

// Connecting to the database and inserting a document
async function run() {
  await client.connect();
  const db = client.db("myDatabase");
  const usersCollection = db.collection("users");

  // Inserting a new user document
  const result = await usersCollection.insertOne({
    name: "John Doe",
    age: 28,
    email: "[email protected]"
  });

  console.log(`New user inserted with ID: ${result.insertedId}`);
}

run().catch(console.error).finally(() => client.close());

Explanation:

  • In this example, we connect to the myDatabase database and the users collection.
  • A new user document is inserted with fields: name, age, and email.
  • The insertedId field contains the unique identifier for the newly inserted document.

2. find: Querying Documents

The find method is used to retrieve documents from a collection. It can return all documents or be filtered based on specific conditions.

Syntax:

javascriptCopyEditdb.collection.find(query, projection)
  • query (Optional): The filter conditions to apply on the documents.
  • projection (Optional): Specifies the fields to include or exclude from the returned documents.

Example:

javascriptCopyEdit// Finding users with age greater than 25
async function findUsers() {
  await client.connect();
  const db = client.db("myDatabase");
  const usersCollection = db.collection("users");

  const users = await usersCollection.find({ age: { $gt: 25 } }).toArray();
  console.log("Users found: ", users);
}

findUsers().catch(console.error).finally(() => client.close());

Explanation:

  • The query { age: { $gt: 25 } } retrieves all documents where the age field is greater than 25.
  • The toArray() method is used to return the results as an array of documents.

Projection Example:

If you only want specific fields in the result, use the projection argument:

javascriptCopyEditconst users = await usersCollection.find({}, { projection: { name: 1, email: 1 } }).toArray();

This query will only return the name and email fields for all documents in the users collection.


3. updateOne: Updating a Single Document

The updateOne method is used to modify an existing document in a collection. It updates only the first document that matches the query criteria.

Syntax:

javascriptCopyEditdb.collection.updateOne(query, update, options)
  • query: The filter condition used to find the document to update.
  • update: The update operations to perform (e.g., $set, $inc).
  • options (Optional): Options to modify the update behavior (e.g., upsert to insert a new document if no match is found).

Example:

javascriptCopyEdit// Updating the age of a user by name
async function updateUser() {
  await client.connect();
  const db = client.db("myDatabase");
  const usersCollection = db.collection("users");

  const result = await usersCollection.updateOne(
    { name: "John Doe" }, // Query to find the user
    { $set: { age: 29 } } // Update operation to set new age
  );

  console.log(`${result.matchedCount} document(s) matched, ${result.modifiedCount} document(s) updated.`);
}

updateUser().catch(console.error).finally(() => client.close());

Explanation:

  • The query { name: "John Doe" } searches for the user with the name “John Doe”.
  • The update operation { $set: { age: 29 } } updates the user’s age to 29.
  • The result object contains matchedCount (number of matched documents) and modifiedCount (number of documents actually updated).

4. deleteOne: Deleting a Single Document

The deleteOne method is used to delete a single document that matches the specified query. Like updateOne, it will only delete the first document that matches the query condition.

Syntax:

javascriptCopyEditdb.collection.deleteOne(query)
  • query: The filter condition used to find the document to delete.

Example:

javascriptCopyEdit// Deleting a user by name
async function deleteUser() {
  await client.connect();
  const db = client.db("myDatabase");
  const usersCollection = db.collection("users");

  const result = await usersCollection.deleteOne({ name: "John Doe" });

  console.log(`${result.deletedCount} document(s) deleted.`);
}

deleteUser().catch(console.error).finally(() => client.close());

Explanation:

  • The query { name: "John Doe" } identifies the document to be deleted.
  • The deletedCount field in the result indicates how many documents were deleted (in this case, it should be 1 if the document exists).

Conclusion

The basic CRUD operations in MongoDB are fundamental for interacting with your data. Here’s a quick summary of what we’ve covered:

  • insertOne: Insert a single document into a collection.
  • find: Retrieve documents from a collection based on specified query conditions.
  • updateOne: Modify a single document that matches the query conditions.
  • deleteOne: Delete a single document that matches the query conditions.

These operations form the building blocks for interacting with MongoDB, whether you’re working on a small application or integrating MongoDB into a larger system. Mastering these operations will enable you to efficiently manage and manipulate data in MongoDB.