AppDividend
Latest Code Tutorials

MongoDB CRUD Operations Tutorial With Example

332

Get real time updates directly on you device, subscribe now.

MongoDB CRUD Operations Tutorial With Example is today’s leading topic. MongoDB stores data in the form of BSON – Binary encoded JSON documents which supports a substantial, rich collection of types. Namely, Fields in BSON documents may hold arrays of values or embedded documents as a requirement. The record in MongoDB is a document which is described below and a data structure formed of field and value pairs.

Want to learn to code, gain a new skill and get a new job. Check out this amazing program

MongoDB CRUD Operations Tutorial

CRUD operations refer to the basic Create(Insert), Read, Update and Delete operations.

#1: Start Mongo Server and Mongo Shell

Now, first start the mongo server using the following command.

mongod

Also, start the mongo shell using the following command.

mongo

#2: Create a database and collection.

Now, switch to an existing database or create a new Mongodb database using the following command.

use crud

So, we switched to that database.

Now, create a collection using the following command. Let us call the collection operate.

db.createCollection("operate")

So, the collection is created. MongoDB stores the documents in the collections. Collections are somewhat same as tables in relational databases. If the collection does not exist then MongoDB creates the collection for you when you first store data for that collection.

#3: Create Operations in MongoDB

Create or insert operations add new documents to the collection. If the collection does not currently exist then insert operations will create the collection.

The command db.collection.insert() will perform the insert operation into the collection of the document.

db.operate.insert({
	enrollno: "110470116021",
	name: "Krunal Lathiya",
        college: "VVP Engineering College",
	course: {
		courseName: "BE IT",
		duration: "4 Years"
	},
	address: {
		city: "Rajkot",
		state: "Gujarat",
		country: "India"
	}
})

It will insert a document in MongoDB.

You can check it by fetching that document using this query.

db.operate.find().pretty()

 

MongoDB CRUD Operations Tutorial With Example

# Insert Multiple Documents in MongoDB

MongoDB provides us the following methods to insert the documents into a collection.

  • db.collection.insertMany()

The syntax is following.

db.collection.insertMany(
   [ <document 1> , <document 2>, ... ],
   {
      writeConcern: <document>,
      ordered: <boolean>
   }
)

It returns the following document containing:

Earn a Tech Degree and get the skills like Frontend Development or Javascript Development that can help you to launch a career. Checkout this amazing program
  • A boolean acknowledged as valid if the operation ran with write concern or false if write concern was disabled.
  • An array of _id for each successfully inserted documents.

We can insertMany documents like the following code.

db.operate.insertMany([{
	enrollno: "110470116021",
	name: "Krunal Lathiya",
  college: "VVP Engineering College",
	course: {
		courseName: "BE IT",
		duration: "4 Years"
	},
	address: {
		city: "Rajkot",
		state: "Gujarat",
		country: "India"
	}
},{
  enrollno: "110470116022",
	name: "Rushikesh Vekariya",
  college: "VVP Engineering College",
	course: {
		courseName: "BE IT",
		duration: "4 Years"
	},
	address: {
		city: "Rajkot",
		state: "Gujarat",
		country: "India"
	}
}])

 

MongoDB CRUD Operations

#4: MongoDB Read Operations

Read operations retrieves the documents from the collection; i.e., queries the collection for the documents. MongoDB provides us the following methods to read the documents from the collection.

db.collection.find()

Let us retrieve all the documents using the following query.

 

MongoDB Read Operations

You can specify the query filters or criteria that identify the documents to return.

db.operate.find().limit(2)

Also, we can get the pretty results.

db
 .operate
 .find()
 .limit(2)
 .pretty()

#5: MongoDB Update Operations

Update operations modify existing documents in the collection. MongoDB provides us the following methods to update the documents of the collection.

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

You can write the update query in MongoDB like below.

db.operate.updateOne(
  { name: "Rushikesh Vekariya" },
  {
    $set: {college: "Marwadi"}
  }
)

 

MongoDB Update Operations

In MongoDB, the update operations target the single collection. All the write operations in MongoDB are atomic on the level of the single document.

We can also run an update on many documents like following.

db.operate.updateMany(
  { name: "Krunal Lathiya" },
  {
    $set: {city: "Jetpur"}
  }
)

In the operate collection, we have two documents whose name is Krunal Lathiya so that it will update both the documents using updateMany.

The db.collection.replaceOne() replaces a single document within the collection based on the filter.

The replaceOne() method has the following syntax.

db.collection.replaceOne(
   <filter>,
   <replacement>,
   {
     upsert: <boolean>,
     writeConcern: <document>,
     collation: <document>
   }
)

#6: MongoDB Delete Operations

The delete operations remove the documents from the collection. MongoDB provides the following methods to delete the documents of the collection.

  • db.collection.deleteOne()
  • db.collection.deleteMany()
db.operate.deleteOne(
  { name : "Krunal Lathiya" }
)

So, it will remove the document which has name Krunal Lathiya.

Same syntax but deleteMany function, which deletes all the documents with the provided name.

Finally, MongoDB CRUD Operations Tutorial With Example is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.