MongoDB is a document-oriented NoSQL database that provides a flexible and scalable data model. It uses BSON(Binary JSON) format to store data.
The CRUD operations in MongoDB are performed using the following methods:
**1) Create Operation:**
To create a new document in MongoDB, the ‘insertOne()‘ or ‘insertMany()‘ method is used. The syntax is as follows:
db.collection.insertOne(document)
db.collection.insertMany(documents)
Here, ‘db.collection‘ refers to the name of the collection in which the document(s) will be inserted. The ‘document‘ parameter is a JSON object that represents the data to be inserted.
Example:
//Insert a single document
db.users.insertOne({name: "John Doe", age: 30})
//Insert multiple documents
db.users.insertMany([
{name: "Bob Smith", age: 25},
{name: "Jane Doe", age: 27},
{name: "Alice Johnson", age: 23}
])
**2) Read Operation:**
To read data from a MongoDB collection, the ‘find()‘ method is used. The syntax is as follows:
db.collection.find(query, projection)
Here, ‘query‘ is an optional parameter that specifies the conditions for selecting documents. The ‘projection‘ parameter is also optional and is used to specify the fields to be returned in the result.
Example:
//Find all documents in a collection
db.users.find()
//Find documents that match a condition
db.users.find({age: {$gt: 25}})
//Find documents and return only selected fields
db.users.find({}, {name: 1, age: 1})
**3) Update Operation:**
To update data in MongoDB, the ‘updateOne()‘ or ‘updateMany()‘ method is used. The syntax is as follows:
db.collection.updateOne(filter, update, options)
db.collection.updateMany(filter, update, options)
Here, ‘filter‘ specifies the condition for selecting the documents to be updated. The ‘update‘ parameter is a JSON object that specifies the modifications to be made.
Example:
//Update a single document
db.users.updateOne({name: "John Doe"}, {$set: {age: 31}})
//Update multiple documents
db.users.updateMany({age: {$lt: 25}}, {$inc: {age: 1}})
**4) Delete Operation:**
To delete data in MongoDB, the ‘deleteOne()‘ or ‘deleteMany()‘ method is used. The syntax is as follows:
db.collection.deleteOne(filter)
db.collection.deleteMany(filter)
Here, ‘filter‘ specifies the condition for selecting the documents to be deleted.
Example:
//Delete a single document
db.users.deleteOne({name: "John Doe"})
//Delete multiple documents
db.users.deleteMany({age: {$lt: 25}})
In conclusion, MongoDB provides a simple but powerful set of functions to perform basic CRUD operations. These functions can be chained together to perform complex queries on the document-oriented data model.