MongoDB CRUD Operations

MongoDB CRUD Operations.

MongoDB is a persistent document-oriented database used to store and process data in the form of documents. As with other database management systems, MongoDB allows you to manage and interact with data through four fundamental types of data operations:

In this article, we will learn all 4 major operations– CREATE, READ, UPDATE, and DELETE that form the CRUD operations in MongoDB.

What is CRUD in MongoDB?
CRUD operations describe the conventions of a user interface that let users view, search, and modify parts of the database. MongoDB provides an elegant way of performing CRUD operations with the programming language of your choice through its drivers.

MongoDB documents are modified by connecting to a server, querying the proper documents, and then changing the setting properties before sending the data back to the database to be updated.

When it comes to the individual CRUD operations:

  • C:-Create operations, which involve writing data to the database.
  • R:-Read operations, which query a database to retrieve data from it.
  • U:-Update operations, which change data that already exists in a database.
  • D:-Delete operations, which permanently remove data from a database.


Create operation:-

For MongoDB CRUD, if the specified collection doesn't exist, the create operation will create the collection when it's executed. Create operations in MongoDB target a single collection, not multiple collections. Insert operations in MongoDB are atomic on a single document level.

MongoDB provides two different create operations that you can use to insert documents into a collection:

  • db.collection.insertOne()
  • db.collection.insertMany()


First, We need to create collection-

db.createCollection('yourcollectionname');


In above snapshort,we have create collection name "create".

View Existing Collections

To view all existing collections in a MongoDB database use the “show collection command“:


Insert values in collection:-
insertOne():-
As the name indicates, insertOne() allows you to insert one document into the collection. For this example, we’re going to work with a collection called RecordsDB. We can insert a single entry into our collection by calling the insertOne() method on RecordsDB. We then provide the information we want to insert in the form of key-value pairs, establishing the schema.

db.create.insertOne({
    name: "Tajwar",
    age: "6 years",
    species: "Human",
    ownerAddress: "380 W. Fir Ave",
    chipped: true
})
If the create operation is successful, a new document is created. The function will return an object where “acknowledged” is “true” and “insertID” is the newly created “ObjectId.”


insertMany():-
It's possible to insert multiple items at one time by calling the insertMany() method on the desired collection. In this case, we pass multiple items into our chosen collection (RecordsDB) and separate them by commas. Within the parentheses, we use brackets to indicate that we are passing in a list of multiple entries. This is commonly referred to as a nested method.

db.create.insertMany([{
name: "buruno",
age: "6 years",
species: "Dog",
ownerAddress: "380 W. Fir Ave",
chipped: true},
{name: "targen",
age: "4 years",
species: "Cat",
ownerAddress: "521 E. Cortland",
chipped: true}])


Read operations:-
The read operations allow you to supply special query filters and criteria that let you specify which documents you want. The MongoDB documentation contains more information on the available query filters. Query modifiers may also be used to change how many results are returned.

MongoDB has two methods of reading documents from a collection:

db.collection.find()
db.collection.findOne()

find():-
To get all the documents from a collection, we can simply use the find() method on our chosen collection. Executing just the find() method with no arguments will return all records currently in the collection.

 db.create.find();

output:-


In the result, we can see all the records present in the collection. Note that every record has an assigned “ObjectId” mapped to the “_id” key.

If you want to get more specific with a read operation and find a desired subsection of the records, you can use the previously mentioned filtering criteria to choose what results should be returned. One of the most common ways of filtering the results is to search by value.

db.create.find({"species":"Cat"});

output:-


findOne():-

To get one document that satisfies the search criteria, we can simply use the findOne() method on our chosen collection. If multiple documents satisfy the query, this method returns the first document according to the natural order which reflects the order of documents on the disk. If no documents satisfy the search criteria, the function returns null. The function takes the following form of syntax.

db.{collection}.findOne({query}, {projection})

output:-



Update operations:-
Like create operations, update operations operate on a single collection, and they are atomic at a single document level. An update operation takes filters and criteria to select the documents you want to update.

You should be careful when updating documents, as updates are permanent and can’t be rolled back. This applies to delete operations as well.

For MongoDB CRUD, there are three different methods of updating documents:

  • db.collection.updateOne()
  • db.collection.updateMany()
  • db.collection.replaceOne()

updateOne():-
We can update a currently existing record and change a single document with an update operation. To do this, we use the updateOne() method on a chosen collection, which here is “create.” To update a document, we provide the method with two arguments: an update filter and an update action.

 db.create.updateOne({name: "Tajwar"}, {$set:{age: "32 year"}})

output:-



updateMany():-
updateMany() allows us to update multiple items by passing in a list of items, just as we did when inserting multiple items. This update operation uses the same syntax for updating a single document.

db.create.updateMany({name:"Tajwar"}, {$set: {age: 01}})


replaceOne():-
The replaceOne() method replaces a single document in the specified collection. replaceOne() replaces the entire document, meaning fields in the old document not contained in the new one will be lost.

db.create.replaceOne({name: "buruno"}, {name: "Maki"})

output:-



Delete operations:-

Delete operations operate on a single collection, like update and create operations. Delete operations are also atomic for a single document. You can provide delete operations with filters and criteria to specify which documents you would like to delete from a collection. The filter options rely on the same syntax that read operations utilize.

MongoDB has two different methods of deleting records from a collection:

  • db.collection.deleteOne()
  • db.collection.deleteMany()
deleteOne()
deleteOne() removes a document from a specified collection on the MongoDB server. A filter criteria is used to specify the item to delete. It deletes the first record that matches the provided filter.

 db.create.deleteOne({name:"Tajwar"})

output:-



deleteMany():-
deleteMany() is a method used to delete multiple documents from a desired collection with a single delete operation. A list is passed into the method and the individual items are defined with filter criteria as in deleteOne().

db.create.deleteMany({name:"Tajwar"})

output:-



Comments

Popular posts from this blog

MySQL Point in Time Recovery: How To Configure And How Does it Work?

MySQL Replication Switchover: Step-by-Step Guide

Mysql Commercial Mysqlbackup:How to take Differential or Incremental Backup and resotre using mysqlbackup utility in mysql 8.0.37 enterprise edition