0% found this document useful (0 votes)
62 views

MongoDB CURD Operation

The document discusses various CRUD operations in MongoDB such as creating databases and collections, inserting documents, querying documents using find(), updating documents, and deleting documents. It provides the syntax and examples for operations like db.createCollection(), db.insert(), db.find(), db.update(), db.remove(). Methods such as insertOne(), insertMany() are also explained for inserting single and multiple documents.

Uploaded by

Jaimin Patel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views

MongoDB CURD Operation

The document discusses various CRUD operations in MongoDB such as creating databases and collections, inserting documents, querying documents using find(), updating documents, and deleting documents. It provides the syntax and examples for operations like db.createCollection(), db.insert(), db.find(), db.update(), db.remove(). Methods such as insertOne(), insertMany() are also explained for inserting single and multiple documents.

Uploaded by

Jaimin Patel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

UNIT-4

Curd Operation

Q-1 How to Create Database


MongoDB use DATABASE_NAME is used to create database. The command will create a
new database if it doesn't exist, otherwise it will return the existing database.

Syntax

Basic syntax of use DATABASE statement is as follows −


use DATABASE_NAME

If you want to use a database with name <mydb>, then use DATABASE statement would be
as follows −
>use mydb
switched to db mydb

If you want to check your databases list, use the command show dbs.

show dbs

Q-2 How to Drop Database

The dropDatabase() Method


MongoDB db.dropDatabase() command is used to drop a existing database.

Syntax

Basic syntax of dropDatabase() command is as follows −


db.dropDatabase()

This will delete the selected database. If you have not selected any database, then it will
delete default 'test' database.

Example

First, check the list of available databases by using the command, show dbs.
>show dbs
local 0.78125GB
mydb 0.23012GB
test 0.23012GB
>
UNIT-4
Curd Operation

If you want to delete new database <mydb>, then dropDatabase() command would be as
follows −
>use mydb
switched to db mydb
>db.dropDatabase()
>{ "dropped" : "mydb", "ok" : 1 }
>

Q-3 How to Create collection

The createCollection() Method


MongoDB db.createCollection(name, options) is used to create collection.

Syntax

Basic syntax of createCollection() command is as follows −


db.createCollection (name, options)
In the command, name is name of collection to be created. Options is a document and is used
to specify configuration of collection.

Parameter Type Description

Name String Name of the collection to be created

Options Document (Optional) Specify options about


memory size and indexing

Options parameter is optional, so you need to specify only the name of the collection.
Following is the list of options you can use –
UNIT-4
Curd Operation

Field Type Description

capped Boolean (Optional) If true, enables a capped collection. Capped


collection is a fixed size collection that automatically
overwrites its oldest entries when it reaches its maximum size.
If you specify true, you need to specify size parameter also.

autoIndexId Boolean (Optional) If true, automatically create index on _id field.s


Default value is false.

size number (Optional) Specifies a maximum size in bytes for a capped


collection. If capped is true, then you need to specify this
field also.

max number (Optional) Specifies the maximum number of documents


allowed in the capped collection.

While inserting the document, MongoDB first checks size field of capped collection, then it
checks max field.

Examples

Basic syntax of createCollection() method without options is as follows −


>use test
switched to db test
>
db.createCollection("mycollection"db
){ "ok" : 1 }
>
You can check the created collection by using the command show collections.
>show collections
my collection
system. indexes
UNIT-4
Curd Operation

The following example shows the syntax of createCollection () method with few important
options −
> db.createCollection ("mycol", { capped : true, autoIndexID : true, size : 6142800, max :
10000 } ){
"ok" : 0,
"errmsg" : "BSON field 'create.autoIndexID' is an unknown field.",
"code" : 40415,
"codeName" : "Location40415"
}
>
In MongoDB, you don't need to create collection. MongoDB creates collection automatically,
when you insert some document.
>db.tutorialspoint.insert({"name" : "tutorialspoint"}),
WriteResult({ "nInserted" : 1 })
>show collections
mycol
mycollection
system.indexes
tutorialspoint
>

Q-4 How to Drop Collection

The drop() Method


MongoDB's db.collection.drop() is used to drop a collection from the database.

Syntax

Basic syntax of drop() command is as follows −


db.COLLECTION_NAME.drop()

Example

First, check the available collections into your database mydb.


>use mydb
switched to db mydb
>show collections
mycol
mycollection
system.indexes
tutorialspoint
>
UNIT-4
Curd Operation

Now drop the collection with the name mycollection.


>db.mycollection.drop()
true
>
Again check the list of collections into database.
>show collections
mycol
system.indexes
tutorialspoint
>

Q-5 What Data Types are available in MONGODB

MongoDB supports many datatypes. Some of them are −


● String − This is the most commonly used datatype to store the data. String in
MongoDB must be UTF-8 valid.
● Integer − This type is used to store a numerical value. Integer can be 32 bit or 64 bit
depending upon your server.
● Boolean − this type is used to store a Boolean (true/ false) value.
● Double − this type is used to store floating point values.
● Min/ Max keys − this type is used to compare a value against the lowest and highest
BSON elements.
● Arrays − this type is used to store arrays or list or multiple values into one key.
● Timestamp − timestamp. This can be handy for recording when a document has been
modified or added.
● Object − This data type is used for embedded documents.
● Null − This type is used to store a Null value

Q-6 How to Insert Document

The insert () Method


To insert data into MongoDB collection, you need to use
MongoDB's insert() or save() method.

Syntax

The basic syntax of insert() command is as follows −


UNIT-4
Curd Operation

>db.COLLECTION_NAME.insert(document)

Example

> db.users.insert({
... _id : ObjectId("507f191e810c19729de860ea"),
... title: "MongoDB Overview",
... description: "MongoDB is no sql database",
... by: "tutorials point",
... url: "http://www.tutorialspoint.com",
... tags: ['mongodb', 'database', 'NoSQL'],
... likes: 100
... })
WriteResult({ "nInserted" : 1 })
>

The insertOne() method


If you need to insert only one document into a collection you can use this method.

Syntax

The basic syntax of insert() command is as follows −


>db.COLLECTION_NAME.insertOne(document)

Example

Following example creates a new collection named empDetails and inserts a document using
the insertOne() method.
> db.createCollection("empDetails")
{ "ok" : 1 }
> db.empDetails.insertOne(
{
First_Name: "Radhika",
Last_Name: "Sharma",
Date_Of_Birth: "1995-09-26",
e_mail: "[email protected]",
phone: "9848022338"
})
{
"acknowledged" : true,
"insertedId" : ObjectId("5dd62b4070fb13eec3963bea")
}
>
UNIT-4
Curd Operation

The insertMany() method


You can insert multiple documents using the insertMany() method. To this method you need
to pass an array of documents.

Example

Following example inserts three different documents into the empDetails collection using the
insertMany() method.
> db.empDetails.insertMany(
[
{
First_Name: "Radhika",
Last_Name: "Sharma",
Date_Of_Birth: "1995-09-26",
e_mail: "[email protected]",
phone: "9000012345"
},
{
First_Name: "Rachel",
Last_Name: "Christopher",
Date_Of_Birth: "1990-02-16",
e_mail: "[email protected]",
phone: "9000054321"
},
{
First_Name: "Fathima",
Last_Name: "Sheik",
Date_Of_Birth: "1990-02-16",
e_mail: "[email protected]",
phone: "9000054321"
}
]
)
{
"acknowledged" : true,
"insertedIds" : [
ObjectId ("5dd631f270fb13eec3963bed"),
ObjectId("5dd631f270fb13eec3963bee"),
ObjectId("5dd631f270fb13eec3963bef")
]
}
>
UNIT-4
Curd Operation

Q-7 Explain Mongo DB Query Document Using Find () Method

The find() Method


To qWuery data from MongoDB collection, you need to use MongoDB's find() method.

Syntax

The basic syntax of find () method is as follows −


>db.COLLECTION_NAME.find()
find() method will display all the documents in a non-structured way.

Example

Assume we have created a collection named mycol as −


> use sampleDB
switched to db sampleDB
> db.createCollection("mycol")
{ "ok" : 1 }
>
And inserted 3 documents in it using the insert() method as shown below −
> db.mycol.insert([
{
title: "MongoDB Overview",
description: "MongoDB is no SQL database",
by: "tutorials point",
url: "http://www.tutorialspoint.com",
tags: ["mongodb", "database", "NoSQL"],
likes: 100
},
{
title: "NoSQL Database",
description: "NoSQL database doesn't have tables",
by: "tutorials point",
url: "http://www.tutorialspoint.com",
tags: ["mongodb", "database", "NoSQL"],
likes: 20,
comments: [
{
user:"user1",
message: "My first comment",
dateCreated: new Date(2013,11,10,2,35),
like: 0
}
UNIT-4
Curd Operation

]
}
])
Following method retrieves all the documents in the collection −
> db.mycol.find()
{ "_id" : ObjectId("5dd4e2cc0821d3b44607534c"), "title" : "MongoDB Overview",
"description" : "MongoDB is no SQL database", "by" : "tutorials point", "url" :
"http://www.tutorialspoint.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100
}
{ "_id" : ObjectId("5dd4e2cc0821d3b44607534d"), "title" : "NoSQL Database",
"description" : "NoSQL database doesn't have tables", "by" : "tutorials point", "url" :
"http://www.tutorialspoint.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 20,
"comments" : [ { "user" : "user1", "message" : "My first comment", "dateCreated" :
ISODate("2013-12-09T21:05:00Z"), "like" : 0 } ] }
>

The pretty() Method


To display the results in a formatted way, you can use pretty() method.

Syntax

>db.COLLECTION_NAME.find().pretty()

Example

Following example retrieves all the documents from the collection named mycol and arranges
them in an easy-to-read format.
> db.mycol.find().pretty()
{
"_id" : ObjectId("5dd4e2cc0821d3b44607534c"),
"title" : "MongoDB Overview",
"description" : "MongoDB is no SQL database",
"by" : "tutorials point",
"url" : "http://www.tutorialspoint.com",
"tags" : [
"mongodb",
"database",
"NoSQL" ],
"likes" : 100
}
{
"_id" : ObjectId("5dd4e2cc0821d3b44607534d"),
"title" : "NoSQL Database",
"description" : "NoSQL database doesn't have tables",
UNIT-4
Curd Operation

"by" : "tutorials point",


"url" : "http://www.tutorialspoint.com",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 20,
"comments" : [
{
"user" : "user1",
"message" : "My first comment",
"dateCreated" : ISODate("2013-12-09T21:05:00Z"),
"like" : 0
}
]
}

The findOne() method


Apart from the find() method, there is findOne() method, that returns only one document.

Syntax

>db.COLLECTIONNAME.findOne()

Example

Following example retrieves the document with title MongoDB Overview.


> db.mycol.findOne({title: "MongoDB Overview"})
{
"_id" : ObjectId("5dd6542170fb13eec3963bf0"),
"title" : "MongoDB Overview",
"description" : "MongoDB is no SQL database",
"by" : "tutorials point",
"url" : "http://www.tutorialspoint.com",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 100
}
UNIT-4
Curd Operation

Q-8 Explain update() & save() method in MongoDB


MongoDB's update() and save() methods are used to update document into a collection. The
update() method updates the values in the existing document while the save() method replaces
the existing document with the document passed in save() method.
MongoDB Update() Method
The update() method updates the values in the existing document.

Syntax

The basic syntax of update() method is as follows −


>db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA)

Example

Consider the mycol collection has the following data.


{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}
Following example will set the new title 'New MongoDB Tutorial' of the documents whose
title is 'MongoDB Overview'.
>db.mycol.update({'title':'MongoDB Overview'},{$set:{'title':'New MongoDB Tutorial'}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
>db.mycol.find()
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"New MongoDB Tutorial"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}
>
By default, MongoDB will update only a single document. To update multiple documents,
you need to set a parameter 'multi' to true.
>db.mycol.update({'title':'MongoDB Overview'},
{$set:{'title':'New MongoDB Tutorial'}},{multi:true})

MongoDB Save() Method


The save() method replaces the existing document with the new document passed in the save()
method.

Syntax

The basic syntax of MongoDB save() method is shown below −


>db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})
UNIT-4
Curd Operation

Example

Following example will replace the document with the _id '5983548781331adf45ec5'.
>db.mycol.save(
{
"_id" : ObjectId("507f191e810c19729de860ea"),
"title":"Tutorials Point New Topic",
"by":"Tutorials Point"
}
)
WriteResult({
"nMatched" : 0,
"nUpserted" : 1,
"nModified" : 0,
"_id" : ObjectId("507f191e810c19729de860ea")
})
>db.mycol.find()
{ "_id" : ObjectId("507f191e810c19729de860e6"), "title":"Tutorials Point New Topic",
"by":"Tutorials Point"}
{ "_id" : ObjectId("507f191e810c19729de860e6"), "title":"NoSQL Overview"}
{ "_id" : ObjectId("507f191e810c19729de860e6"), "title":"Tutorials Point Overview"}
>

MongoDB findOneAndUpdate() method


The findOneAndUpdate() method updates the values in the existing document.

Syntax

The basic syntax of findOneAndUpdate() method is as follows −


>db.COLLECTION_NAME.findOneAndUpdate(SELECTIOIN_CRITERIA,
UPDATED_DATA)

Example

Assume we have created a collection named empDetails and inserted three documents in it as
shown below −
> db.empDetails.insertMany(
[
{
First_Name: "Radhika",
Last_Name: "Sharma",
Age: "26",
e_mail: "[email protected]",
phone: "9000012345"
UNIT-4
Curd Operation

},
{
First_Name: "Rachel",
Last_Name: "Christopher",
Age: "27",
e_mail: "[email protected]",
phone: "9000054321"
},
{
First_Name: "Fathima",
Last_Name: "Sheik",
Age: "24",
e_mail: "[email protected]",
phone: "9000054321"
}
]
)
Following example updates the age and email values of the document with name 'Radhika'.
> db.empDetails.findOneAndUpdate(
{First_Name: 'Radhika'},
{ $set: { Age: '30',e_mail: '[email protected]'}}
)
{
"_id" : ObjectId("5dd6636870fb13eec3963bf5"),
"First_Name" : "Radhika",
"Last_Name" : "Sharma",
"Age" : "30",
"e_mail" : "[email protected]",
"phone" : "9000012345"
}

MongoDB updateOne() method


This methods updates a single document which matches the given filter.

Syntax

The basic syntax of updateOne() method is as follows −


>db.COLLECTION_NAME.updateOne(<filter>, <update>)

Example

> db.empDetails.updateOne(
{First_Name: 'Radhika'},
{ $set: {Age: '30',e_mail: '[email protected]'}}
UNIT-4
Curd Operation

)
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 0 }

MongoDB updateMany() method


The updateMany() method updates all the documents that matches the given filter.

Syntax

The basic syntax of updateMany() method is as follows −


>db.COLLECTION_NAME.update(<filter>, <update>)

Example

> db.empDetails.updateMany(
{Age:{ $gt: "25" }},
{ $set: { Age: '00'}}
)
{ "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 }
You can see the updated values if you retrieve the contents of the document using the find
method as shown below −
> db.empDetails.find()
{ "_id" : ObjectId("5dd6636870fb13eec3963bf5"), "First_Name" : "Radhika", "Last_Name" :
"Sharma", "Age" : "00", "e_mail" : "[email protected]", "phone" :
"9000012345" }
{ "_id" : ObjectId("5dd6636870fb13eec3963bf6"), "First_Name" : "Rachel", "Last_Name" :
"Christopher", "Age" : "00", "e_mail" : "[email protected]", "phone" :
"9000054321" }
{ "_id" : ObjectId("5dd6636870fb13eec3963bf7"), "First_Name" : "Fathima", "Last_Name" :
"Sheik", "Age" : "24", "e_mail" : "[email protected]", "phone" :
"9000054321" }
>

Q-9 Explain Delete Document from a Collection

The remove() Method


MongoDB's remove () method is used to remove a document from the collection. remove()
method accepts two parameters. One is deletion criteria and second is justOne flag.
● Deletion criteria − (Optional) deletion criteria according to documents will be
removed.
● Just One − (Optional) if set to true or 1, then remove only one document.
UNIT-4
Curd Operation

Syntax

Basic syntax of remove() method is as follows −


>db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)

Example

Consider the mycol collection has the following data.


{_id : ObjectId("507f191e810c19729de860e1"), title: "MongoDB Overview"},
{_id : ObjectId("507f191e810c19729de860e2"), title: "NoSQL Overview"},
{_id : ObjectId("507f191e810c19729de860e3"), title: "Tutorials Point Overview"}
Following example will remove all the documents whose title is 'MongoDB Overview'.
>db.mycol.remove({'title':'MongoDB Overview'})
WriteResult({"nRemoved" : 1})
> db.mycol.find()
{"_id" : ObjectId("507f191e810c19729de860e2"), "title" : "NoSQL Overview" }
{"_id" : ObjectId("507f191e810c19729de860e3"), "title" : "Tutorials Point Overview" }

Remove Only One


If there are multiple records and you want to delete only the first record, then set just
One parameter in remove() method.

>db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)

Remove All Documents


If you don't specify deletion criteria, then MongoDB will delete whole documents from the
collection. This is equivalent of SQL's truncate command.
> db.mycol.remove({})
WriteResult({ "nRemoved" : 2 })
> db.mycol.find()
>

Q-10 Explain Mongo DB Projection

In MongoDB, projection means selecting only the necessary data rather than selecting whole
of the data of a document. If a document has 5 fields and you need to show only 3, then select
only 3 fields from them.

The find() Method


MongoDB's find() method, explained in MongoDB Query Document accepts second
optional parameter that is list of fields that you want to retrieve. In MongoDB, when you
UNIT-4
Curd Operation

execute find() method, then it displays all fields of a document. To limit this, you need to set
a list of fields with value 1 or 0. 1 is used to show the field while 0 is used to hide the fields.

Syntax

The basic syntax of find() method with projection is as follows −


>db.COLLECTION_NAME.find({},{KEY:1})

Example

Consider the collection mycol has the following data −


{_id : ObjectId("507f191e810c19729de860e1"), title: "MongoDB Overview"},
{_id : ObjectId("507f191e810c19729de860e2"), title: "NoSQL Overview"},
{_id : ObjectId("507f191e810c19729de860e3"), title: "Tutorials Point Overview"}
Following example will display the title of the document while querying the document.
>db.mycol.find({},{"title":1,_id:0})
{"title":"MongoDB Overview"}
{"title":"NoSQL Overview"}
{"title":"Tutorials Point Overview"}
>

You might also like