0% found this document useful (0 votes)
44 views20 pages

Mongo DB

- MongoDB is a cross-platform document-oriented database that provides high performance, high availability, and easy scalability. It uses collections and documents rather than tables and rows. - A database contains collections, collections contain documents, and documents contain key-value pairs. Documents can have different fields and a dynamic schema. - MongoDB provides advantages over relational databases like flexible schemas, scalability, and ease of development. It is commonly used for big data, content management, mobile applications, and user data management.

Uploaded by

GAURAV KADVE
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
44 views20 pages

Mongo DB

- MongoDB is a cross-platform document-oriented database that provides high performance, high availability, and easy scalability. It uses collections and documents rather than tables and rows. - A database contains collections, collections contain documents, and documents contain key-value pairs. Documents can have different fields and a dynamic schema. - MongoDB provides advantages over relational databases like flexible schemas, scalability, and ease of development. It is commonly used for big data, content management, mobile applications, and user data management.

Uploaded by

GAURAV KADVE
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 20

MongoDB is a cross-platform, document oriented database that provides, high

performance, high availability, and easy scalability. MongoDB works on concept of


collection and document.

Database
Database is a physical container for collections. Each database gets its own set of
files on the file system. A single MongoDB server typically has multiple databases.

Collection
Collection is a group of MongoDB documents. It is the equivalent of an RDBMS table.
A collection exists within a single database. Collections do not enforce a schema.
Documents within a collection can have different fields. Typically, all documents in a
collection are of similar or related purpose.

Document
A document is a set of key-value pairs. Documents have dynamic schema. Dynamic
schema means that documents in the same collection do not need to have the same
set of fields or structure, and common fields in a collection's documents may hold
different types of data.

Any relational database has a typical schema design that shows number of tables
and the relationship between these tables. While in MongoDB, there is no concept of
relationship.

Advantages of MongoDB over RDBMS


• Schema less − MongoDB is a document database in which one collection
holds different documents. Number of fields, content and size of the document
can differ from one document to another.
• Structure of a single object is clear.
• No complex joins.
• Deep query-ability. MongoDB supports dynamic queries on documents using
a document-based query language that's nearly as powerful as SQL.
• Tuning.
• Ease of scale-out − MongoDB is easy to scale.
• Conversion/mapping of application objects to database objects not needed.
• Uses internal memory for storing the (windowed) working set, enabling faster
access of data.

Why Use MongoDB?


• Document Oriented Storage − Data is stored in the form of JSON style
documents.
• Index on any attribute
• Replication and high availability
• Auto-Sharding
• Rich queries
• Fast in-place updates
• Professional support by MongoDB

Where to Use MongoDB?


• Big Data
• Content Management and Delivery
• Mobile and Social Infrastructure
• User Data Management
• Data Hub

Install and Set the environment:


https://www.tutorialspoint.com/mongodb/mongodb_environment.htm

Basic Commands

The use Command


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
Example
If you want to use a database with name <mydb>, then use DATABASE statement
would be as follows −
>use mydb
switched to db mydb

To check your currently selected database, use the command db


>db
mydb
If you want to check your databases list, use the command show dbs.
>show dbs
local 0.78125GB
test 0.23012GB
Your created database (mydb) is not present in list. To display database, you need
to insert at least one document into it.
>db.collection1.insert({"name":"abc"})
>show dbs
local 0.78125GB
mydb 0.23012GB
test 0.23012GB

In MongoDB default database is test. If you didn't create any database, then
collections will be stored in test 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
>

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 }
>

Now check list of databases.


>show dbs
local 0.78125GB
test 0.23012GB
>

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


>use test
switched to db test
>db.createCollection("mycollection")
{ "ok" : 1 }
>

You can check the created collection by using the command show collections.
>show collections
mycollection
system.indexes

In MongoDB, you don't need to create collection. MongoDB creates collection


automatically, when you insert some document.
>db.collection2.insert({"name" : "def"}),
WriteResult({ "nInserted" : 1 })

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

Now drop the collection with the name mycollection.


>db.mycollection.drop()
true
>

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 − ctimestamp. This can be handy for recording when a document
has been modified or added.
• Object − This datatype is used for embedded documents.
• Null − This type is used to store a Null value.
• Symbol − This datatype is used identically to a string; however, it's generally
reserved for languages that use a specific symbol type.
• Date − This datatype is used to store the current date or time in UNIX time
format. You can specify your own date time by creating object of Date and
passing day, month, year into it.
• Object ID − This datatype is used to store the document’s ID.
• Binary data − This datatype is used to store binary data.
• Code − This datatype is used to store JavaScript code into the document.
• Regular expression − This datatype is used to store regular expression.

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 −
>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: "radhika_sharma.123@gmail.com",
phone: "9848022338"
})
{
"acknowledged" : true,
"insertedId" : ObjectId("5dd62b4070fb13eec3963bea")
}
>

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: "radhika_sharma.123@gmail.com",
phone: "9000012345"
},
{
First_Name: "Rachel",
Last_Name: "Christopher",
Date_Of_Birth: "1990-02-16",
e_mail: "Rachel_Christopher.123@gmail.com",
phone: "9000054321"
},
{
First_Name: "Fathima",
Last_Name: "Sheik",
Date_Of_Birth: "1990-02-16",
e_mail: "Fathima_Sheik.123@gmail.com",
phone: "9000054321"
}
]
)
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("5dd631f270fb13eec3963bed"),
ObjectId("5dd631f270fb13eec3963bee"),
ObjectId("5dd631f270fb13eec3963bef")
]
}
>

The find() Method


To query 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.

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()
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"})

RDBMS Where Clause Equivalents in MongoDB


To query the document on the basis of some condition, you can use following
operations.

Operatio Syntax Example RDBMS


n Equivalen
t

Equality {<key>:{$eg;<value>}} db.mycol.find({"by":"tutorials where by


point"}).pretty() = 'tutorials
point'

Less {<key>:{$lt:<value>}} db.mycol.find({"likes":{$lt:50}}).pretty( where


Than ) likes < 50

Less {<key>:{$lte:<value>}} db.mycol.find({"likes":{$lte:50}}).prett where


Than y() likes <=
Equals 50

Greater {<key>:{$gt:<value>}} db.mycol.find({"likes":{$gt:50}}).pretty where


Than () likes > 50

Greater {<key>:{$gte:<value>}} db.mycol.find({"likes":{$gte:50}}).prett where


Than y() likes >=
Equals 50
Not {<key>:{$ne:<value>}} db.mycol.find({"likes":{$ne:50}}).prett where
Equals y() likes != 50

Values in {<key>:{$in:[<value1>, db.mycol.find({"name":{$in:["Raj", Where


an array <value2>,……<valueN> "Ram", "Raghu"]}}).pretty() name
]}} matches
any of the
value in
:["Raj",
"Ram",
"Raghu"]

Values {<key>:{$nin:<value>}} db.mycol.find({"name":{$nin:["Ramu", Where


not in an "Raghav"]}}).pretty() name
array values is
not in the
array
:["Ramu",
"Raghav"]
or, doesn’t
exist at all

AND in MongoDB
Syntax
To query documents based on the AND condition, you need to use $and keyword.
Following is the basic syntax of AND −
>db.mycol.find({ $and: [ {<key1>:<value1>}, { <key2>:<value2>} ]
})
Example
Following example will show all the tutorials written by 'tutorials point' and whose title
is 'MongoDB Overview'.
> db.mycol.find({$and:[{"by":"tutorials point"},{"title":
"MongoDB Overview"}]}).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
}
>

For the above given example, equivalent where clause will be ' where by = 'tutorials
point' AND title = 'MongoDB Overview' '. You can pass any number of key, value
pairs in find clause.

OR in MongoDB
Syntax
To query documents based on the OR condition, you need to use $or keyword.
Following is the basic syntax of OR −
>db.mycol.find(
{
$or: [
{key1: value1}, {key2:value2}
]
}
).pretty()
Example
Following example will show all the tutorials written by 'tutorials point' or whose title
is 'MongoDB Overview'.
>db.mycol.find({$or:[{"by":"tutorials point"},{"title": "MongoDB
Overview"}]}).pretty()
{
"_id": ObjectId(7df78ad8902c),
"title": "MongoDB Overview",
"description": "MongoDB is no sql database",
"by": "tutorials point",
"url": "http://www.tutorialspoint.com",
"tags": ["mongodb", "database", "NoSQL"],
"likes": "100"
}
>

Using AND and OR Together


Example
The following example will show the documents that have likes greater than 10 and
whose title is either 'MongoDB Overview' or by is 'tutorials point'. Equivalent SQL
where clause is 'where likes>10 AND (by = 'tutorials point' OR title = 'MongoDB
Overview')'
>db.mycol.find({"likes": {$gt:10}, $or: [{"by": "tutorials
point"},
{"title": "MongoDB Overview"}]}).pretty()
{
"_id": ObjectId(7df78ad8902c),
"title": "MongoDB Overview",
"description": "MongoDB is no sql database",
"by": "tutorials point",
"url": "http://www.tutorialspoint.com",
"tags": ["mongodb", "database", "NoSQL"],
"likes": "100"
}
>

NOR in MongoDB
Syntax
To query documents based on the NOT condition, you need to use $not keyword.
Following is the basic syntax of NOT −
>db.COLLECTION_NAME.find(
{
$not: [
{key1: value1}, {key2:value2}
]
}
)
Example
Assume we have inserted 3 documents in the collection empDetails as shown below

db.empDetails.insertMany(
[
{
First_Name: "Radhika",
Last_Name: "Sharma",
Age: "26",
e_mail: "radhika_sharma.123@gmail.com",
phone: "9000012345"
},
{
First_Name: "Rachel",
Last_Name: "Christopher",
Age: "27",
e_mail: "Rachel_Christopher.123@gmail.com",
phone: "9000054321"
},
{
First_Name: "Fathima",
Last_Name: "Sheik",
Age: "24",
e_mail: "Fathima_Sheik.123@gmail.com",
phone: "9000054321"
}
]
)

Following example will retrieve the document(s) whose first name is not "Radhika"
and last name is not "Christopher"
> db.empDetails.find(
{
$nor:[
40
{"First_Name": "Radhika"},
{"Last_Name": "Christopher"}
]
}
).pretty()
{
"_id" : ObjectId("5dd631f270fb13eec3963bef"),
"First_Name" : "Fathima",
"Last_Name" : "Sheik",
"Age" : "24",
"e_mail" : "Fathima_Sheik.123@gmail.com",
"phone" : "9000054321"
}

NOT in MongoDB
Syntax
To query documents based on the NOT condition, you need to use $not keyword
following is the basic syntax of NOT −
>db.COLLECTION_NAME.find(
{
$NOT: [
{key1: value1}, {key2:value2}
]
}
).pretty()
Example
Following example will retrieve the document(s) whose age is not greater than 25
> db.empDetails.find( { "Age": { $not: { $gt: "25" } } } )
{
"_id" : ObjectId("5dd6636870fb13eec3963bf7"),
"First_Name" : "Fathima",
"Last_Name" : "Sheik",
"Age" : "24",
"e_mail" : "Fathima_Sheik.123@gmail.com",
"phone" : "9000054321"
}
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})
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: "radhika_sharma.123@gmail.com",
phone: "9000012345"
},
{
First_Name: "Rachel",
Last_Name: "Christopher",
Age: "27",
e_mail: "Rachel_Christopher.123@gmail.com",
phone: "9000054321"
},
{
First_Name: "Fathima",
Last_Name: "Sheik",
Age: "24",
e_mail: "Fathima_Sheik.123@gmail.com",
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: 'radhika_newemail@gmail.com'}}
)
{
"_id" : ObjectId("5dd6636870fb13eec3963bf5"),
"First_Name" : "Radhika",
"Last_Name" : "Sharma",
"Age" : "30",
"e_mail" : "radhika_newemail@gmail.com",
"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: 'radhika_newemail@gmail.com'}}
)
{ "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" :
"radhika_newemail@gmail.com", "phone" : "9000012345" }
{ "_id" : ObjectId("5dd6636870fb13eec3963bf6"), "First_Name" :
"Rachel", "Last_Name" : "Christopher", "Age" : "00", "e_mail" :
"Rachel_Christopher.123@gmail.com", "phone" : "9000054321" }
{ "_id" : ObjectId("5dd6636870fb13eec3963bf7"), "First_Name" :
"Fathima", "Last_Name" : "Sheik", "Age" : "24", "e_mail" :
"Fathima_Sheik.123@gmail.com", "phone" : "9000054321" }
>

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.
• justOne − (Optional) if set to true or 1, then remove only one document.
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 justOne 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()
>

The sort() Method


To sort documents in MongoDB, you need to use sort() method. The method accepts
a document containing a list of fields along with their sorting order. To specify sorting
order 1 and -1 are used. 1 is used for ascending order while -1 is used for descending
order.
Syntax
The basic syntax of sort() method is as follows −
>db.COLLECTION_NAME.find().sort({KEY:1})
Example
Consider the collection myycol 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 documents sorted by title in the descending order.
>db.mycol.find({},{"title":1,_id:0}).sort({"title":-1})
{"title":"Tutorials Point Overview"}
{"title":"NoSQL Overview"}
{"title":"MongoDB Overview"}
>

Please note, if you don't specify the sorting preference, then sort() method will
display the documents in ascending order.
1. Open cmd
2. cd C:\Program Files\MongoDB\Server\5.0\bin
3. mongo.exe[to start the nosql database]
4. > [See this symbol to make sure mongodb is running now]
5. type “show dbs”
6. use newdb [creating new db]
7. show dbs [as no collection is created, it will not show that db]
8. db.createCollection(“empinfo”)
9. show dbs[now, newdb is shown in the list]
10. db.empinfo.insert({"name":"abc","id":"1001"})
11. db.empinfo.insert({"name":"def","id":"1002"})
12. db [shows the database]
13. show collections[ list all collections in that database]
14. db.empinfo.find() [displays all documents in the collection]
15. db.empinfo.insert({"name":"ghi","id":"1003","phno":"9192939495"})
16. db.empinfo.find()
17. db.empinfo.find({"name":"abc"}) [displays the infor where name=”abc”]
18. db.empinfo.update({"id":"1001"},{$set:{"phno":"8182838485","age":25,"Place":"Vellore"}})
19. db.empinfo.find()

{ "_id" : ObjectId("61a4f985b7372617da7f6742"), "name" : "abc", "id" : "1001", "Place" :


"Vellore", "age" : 25, "phno" : "8182838485" }
{ "_id" : ObjectId("61a4f9acb7372617da7f6743"), "name" : "def", "id" : "1002" }
{ "_id" : ObjectId("61a4fa2ab7372617da7f6744"), "name" : "ghi", "id" : "1003", "phno" :
"9192939495" }

20. db.empinfo.update({"id":"1002"},{$set:{"age":28}})
21. db.empinfo.update({"id":"1003"},{$set:{"age":32}})
22. db.empinfo.find()

{ "_id" : ObjectId("61a4f985b7372617da7f6742"), "name" : "abc", "id" : "1001", "Place" :


"Vellore", "age" : 25, "phno" : "8182838485" }

{ "_id" : ObjectId("61a4f9acb7372617da7f6743"), "name" : "def", "id" : "1002", "age" : 28 }

{ "_id" : ObjectId("61a4fa2ab7372617da7f6744"), "name" : "ghi", "id" : "1003", "phno" :


"9192939495", "age" : 32 }

23. db.emp.update({"name":"abc"},{$unset:{"age":20}}) [removes age attribute for one


document]
24. db.emp.update({},{$set:{"dept":"scope"}},{multi:true})[sets an attribute for all documents]
25. db.emp.update({},{$unset:{"dept":"scope"}})[removes attribute for first document]
26. db.emp.update({},{$unset:{"dept":"scope"}},{multi:true}) [removes attribute for all
documents]
27. db.emp.find({},{"name":1})[displays only name attribute for all documents]
28. db.emp.find({},{"name":1,"_id":0}).sort({"name":1})[sorts in asc order]
29. db.emp.find({},{"name":1,"_id":0}).sort({"name":-1})[desc order]
30. db.emp.find({},{"name":1,"id":2})[displays two attributes for all documents]
31. db.emp.find({"id":"1003"},{"name":1,"id":2})[two attributes for particular document]
32. db.emp.find({"eid":"1003"},{"name":1,"_id":0})[displays only name attribute, removes
default id attribute in the result while displaying]
33. db.empinfo.find({"age":{$lt:30}})
34. db.empinfo.find({"age":{$gt:27}})
35. db.empinfo.find({$and:[{"age":{$gt:27}},{"age":{$lt:30}}]})
36. db.empinfo.find({$or:[{"Place":"Vellore"},{"age":{$gt:30}}]})
37. db.empinfo.find({"age":{$not:{$gt:28}}})
38. db.empinfo.remove({"id":"1003"})[one document gets deleted]
39. db.empinfo.remove({}) [removes all documents from that collection]
40. db.empinfo.aggregate([{$match:{"age":{$gt:20}}},{$count:"AgeCount"}]);
41. db.empinfo.find()[no documents, as all are removed in previous step]
42. show collections

empinfo

43. db.empinfo.drop()
44. show collections

[shows none]

45. db
newdb [ shows current db]

46. db.dropDatabase()
47. show dbs

You might also like