logologo
  • AI Tools

    DB Query GeneratorMock InterviewResume BuilderLearning Path GeneratorCheatsheet GeneratorAgentic Prompt GeneratorCompany ResearchCover Letter Generator
  • XpertoAI
  • MVP Ready
  • Resources

    CertificationsTopicsExpertsCollectionsArticlesQuestionsVideosJobs
logologo

Elevate Your Coding with our comprehensive articles and niche collections.

Useful Links

  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation
  • About Us

Resources

  • Xperto-AI
  • Certifications
  • Python
  • GenAI
  • Machine Learning

Interviews

  • DSA
  • System Design
  • Design Patterns
  • Frontend System Design
  • ReactJS

Procodebase © 2024. All rights reserved.

Level Up Your Skills with Xperto-AI

A multi-AI agent platform that helps you level up your development skills and ace your interview preparation to secure your dream job.

Launch Xperto-AI

CRUD Operations in MongoDB

author
Generated by
ProCodebase AI

09/11/2024

MongoDB

Sign in to read full article

MongoDB is one of the most popular NoSQL databases, particularly known for its schema-less design and flexibility in handling large volumes of data. Understanding CRUD operations—Create, Read, Update, and Delete—is essential for anyone looking to work with MongoDB efficiently. Let’s dive into these operations and see how they work!

1. Create Operation

The Create operation is used to insert new documents into a collection. In MongoDB, documents are stored in collections, and these documents are represented in BSON (Binary JSON) format.

Example: Inserting a Document

// Connect to your MongoDB database const MongoClient = require('mongodb').MongoClient; async function run() { const client = new MongoClient('mongodb://localhost:27017'); await client.connect(); const database = client.db('sampleDB'); const collection = database.collection('users'); // Create a new document const newUser = { name: "John Doe", age: 30, email: "john.doe@example.com" }; const result = await collection.insertOne(newUser); console.log(`New user created with the following id: ${result.insertedId}`); await client.close(); } run().catch(console.dir);

In this example, we connect to a MongoDB database named sampleDB and insert a new user document into the users collection. The insertOne method returns an object containing the insertedId, which is useful for referencing the newly created document later.

2. Read Operation

The Read operation is crucial for retrieving data from a MongoDB collection. You can fetch single or multiple documents based on different criteria using various MongoDB queries.

Example: Reading Documents

async function readUsers() { const client = new MongoClient('mongodb://localhost:27017'); await client.connect(); const database = client.db('sampleDB'); const collection = database.collection('users'); // Find one user const user = await collection.findOne({ name: "John Doe" }); console.log(user); // Find all users const allUsers = await collection.find({}).toArray(); console.log(allUsers); await client.close(); } readUsers().catch(console.dir);

Here, we retrieve a single user document by filtering based on the user's name. The findOne method returns the first document that matches the specified condition. We also use find({}) with toArray() to get all documents from the users collection.

3. Update Operation

The Update operation allows you to modify existing documents in a MongoDB collection. You can update fields of a single document or multiple documents based on specific criteria.

Example: Updating a Document

async function updateUser() { const client = new MongoClient('mongodb://localhost:27017'); await client.connect(); const database = client.db('sampleDB'); const collection = database.collection('users'); // Update user age const result = await collection.updateOne( { name: "John Doe" }, { $set: { age: 31 } } ); console.log(`${result.modifiedCount} document(s) updated`); await client.close(); } updateUser().catch(console.dir);

In this example, we update the age of the user named "John Doe". The updateOne method takes two parameters: a filter to match the document and an update operator ($set) to specify the changes. The result includes the count of modified documents.

4. Delete Operation

The Delete operation is used to remove documents from a collection. You can delete single or multiple documents based on specified conditions.

Example: Deleting a Document

async function deleteUser() { const client = new MongoClient('mongodb://localhost:27017'); await client.connect(); const database = client.db('sampleDB'); const collection = database.collection('users'); // Delete a user const result = await collection.deleteOne({ name: "John Doe" }); console.log(`${result.deletedCount} document(s) deleted`); await client.close(); } deleteUser().catch(console.dir);

This example demonstrates how to delete a user document by matching the name "John Doe". The deleteOne method returns the count of deleted documents, providing confirmation of the operation's success.

Summary of CRUD Operations

To summarize, we’ve covered the essential CRUD operations in MongoDB, including how to create, read, update, and delete documents in a collection. Each of these operations utilizes specific MongoDB methods and provides a straightforward approach to data manipulation. Embracing these concepts will significantly enhance your ability to work with MongoDB effectively and efficiently!

Feel free to experiment with these examples in your own MongoDB environment, and don't hesitate to dive deeper into more advanced topics as you grow your database skills!

Popular Tags

MongoDBCRUD OperationsDatabase Management

Share now!

Like & Bookmark!

Related Collections

  • Mastering MongoDB: From Basics to Advanced Techniques

    09/11/2024 | MongoDB

Related Articles

  • Indexing and Query Optimization in MongoDB

    09/11/2024 | MongoDB

  • Harnessing the Power of MongoDB Atlas for Seamless Cloud Deployment

    09/11/2024 | MongoDB

  • Introduction to MongoDB and NoSQL Databases

    09/11/2024 | MongoDB

  • Working with BSON and JSON Data Types in MongoDB

    09/11/2024 | MongoDB

  • Real-time Analytics with MongoDB

    09/11/2024 | MongoDB

  • Setting Up Your MongoDB Environment

    09/11/2024 | MongoDB

  • Unlocking the Power of MongoDB for Machine Learning and Data Science

    09/11/2024 | MongoDB

Popular Category

  • Python
  • Generative AI
  • Machine Learning
  • ReactJS
  • System Design