The cart is empty

MongoDB is a document-oriented NoSQL database that allows storing structured data in a format similar to JSON. MongoDB is widely used for its flexibility, scalability, and performance. In this article, we will focus on the basic CRUD (Create, Read, Update, Delete) operations in MongoDB, which are fundamental for data manipulation.

CRUD Operations

CRUD operations represent four basic actions that can be performed on data stored in a database. In the case of MongoDB, these operations are implemented using various methods of the JavaScript API.

Creating (Create)

To create new documents in MongoDB, we use the insertOne() method to insert a single document or insertMany() to insert multiple documents at once into a collection.

db.collection.insertOne({
  name: "John Smith",
  age: 30,
  email: "This email address is being protected from spambots. You need JavaScript enabled to view it."
});

db.collection.insertMany([
  { name: "Peter Johnson", age: 25, email: "This email address is being protected from spambots. You need JavaScript enabled to view it." },
  { name: "Lucy Brown", age: 28, email: "This email address is being protected from spambots. You need JavaScript enabled to view it." }
]);

Reading (Read)

To read documents from MongoDB, we can use the find() method, which allows searching for documents based on various criteria. To retrieve a specific document, we can use findOne().

db.collection.find({ age: { $gt: 25 } }); // Finds all documents with age greater than 25

db.collection.findOne({ name: "John Smith" }); // Finds the first document with the name John Smith

Updating (Update)

Updating documents is done using the updateOne() or updateMany() methods, which allow changing existing documents based on certain criteria.

db.collection.updateOne(
  { name: "John Smith" },
  { $set: { age: 31 } }
); // Updates the age of John Smith to 31

db.collection.updateMany(
  { age: { $lt: 30 } },
  { $inc: { age: 1 } }
); // Increases the age of all persons younger than 30 by 1

Deleting (Delete)

To remove documents, we use the deleteOne() and deleteMany() methods. These methods allow deleting documents that meet certain criteria.

db.collection.deleteOne({ name: "John Smith" }); // Removes the document with the name John Smith

db.collection.deleteMany({ age: { $lt: 30 } }); // Removes all documents with age less than 30

CRUD operations are the basic building blocks for working with databases, including MongoDB. Understanding these operations is crucial for efficient data manipulation and management. MongoDB offers rich capabilities for working with data, whether it's simple data insertion or complex queries. Extensive documentation and community support make it easier for developers to quickly adopt these operations and effectively utilize them in practice.