0% found this document useful (0 votes)
17 views19 pages

Mongo Queries2

The document provides examples of MongoDB operations including creating collections, inserting documents with insertOne() and insertMany(), querying with find() and findOne(), and updating documents with findOneAndUpdate() and updateOne(). It also covers filtering documents using various conditions like equality, less than, greater than, and logical operators such as AND and OR. Additionally, it explains how to sort documents and remove them from collections.
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)
17 views19 pages

Mongo Queries2

The document provides examples of MongoDB operations including creating collections, inserting documents with insertOne() and insertMany(), querying with find() and findOne(), and updating documents with findOneAndUpdate() and updateOne(). It also covers filtering documents using various conditions like equality, less than, greater than, and logical operators such as AND and OR. Additionally, it explains how to sort documents and remove them from collections.
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/ 19

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

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

>db.COLLECTION_NAME.find()
>db.COLLECTION_NAME.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.myc–––––ol.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
}

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

Operation Syntax Example RDBMS


Equivalent

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


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

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


< 50

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


Equals <= 50

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


Than > 50

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


Than >= 50
Equals

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


Equals != 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}
]
}
)
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: "[email protected]",
phone: "9000012345"
},
{
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]'}}
)
{ "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" }
>

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.

use book

switched to db book

> db.book.insert({bid:2,bname: "DBMS priciples", Author: "korth", edition:4});

WriteResult({ "nInserted" : 1 })

> db.book.find()
{ "_id" : ObjectId("6150a0f9f945783949c3ffb3"), "bid" : 2, "bname" : "DBMS priciples", "Author" :
"korth", "edition" : 4 }

> db.book.insert({bid:5,bname: "DBMS priciples", Author: "korth", edition:4});

WriteResult({ "nInserted" : 1 })

> db.book.insert({bid:5,bname: "ADBMS priciples", Author: "Navathe", edition:4});

WriteResult({ "nInserted" : 1 })

> db.book.remove({'bid'=5})

uncaught exception: SyntaxError: missing : after property id :

@(shell):1:21

> db.book.remove({"bid"="5"})

uncaught exception: SyntaxError: missing : after property id :

@(shell):1:21

> db.book.remove({"bid"=5})

uncaught exception: SyntaxError: missing : after property id :

@(shell):1:21

> db.book.remove({"bname": "DBMS priciples"})

WriteResult({ "nRemoved" : 2 })

> db.book.insert({bid:2,bname: "DBMS priciples", Author: "korth", edition:4});

WriteResult({ "nInserted" : 1 })

> db.book.find()

{ "_id" : ObjectId("6150a1b2f945783949c3ffb5"), "bid" : 5, "bname" : "ADBMS priciples", "Author" :


"Navathe", "edition" : 4 }

{ "_id" : ObjectId("6150a40ef945783949c3ffb6"), "bid" : 2, "bname" : "DBMS priciples", "Author" :


"korth", "edition" : 4 }

> db.book.find().pretty();

"_id" : ObjectId("6150a1b2f945783949c3ffb5"),
"bid" : 5,

"bname" : "ADBMS priciples",

"Author" : "Navathe",

"edition" : 4

"_id" : ObjectId("6150a40ef945783949c3ffb6"),

"bid" : 2,

"bname" : "DBMS priciples",

"Author" : "korth",

"edition" : 4

> db.book.find({edition:4}).pretty()

"_id" : ObjectId("6150a1b2f945783949c3ffb5"),

"bid" : 5,

"bname" : "ADBMS priciples",

"Author" : "Navathe",

"edition" : 4

"_id" : ObjectId("6150a40ef945783949c3ffb6"),

"bid" : 2,

"bname" : "DBMS priciples",

"Author" : "korth",
"edition" : 4

> db.book.find({bid: 2}).pretty()

"_id" : ObjectId("6150a40ef945783949c3ffb6"),

"bid" : 2,

"bname" : "DBMS priciples",

"Author" : "korth",

"edition" : 4

> db.book.findOne()

"_id" : ObjectId("6150a1b2f945783949c3ffb5"),

"bid" : 5,

"bname" : "ADBMS priciples",

"Author" : "Navathe",

"edition" : 4

Onl one record to be inserted

db.book.insertOne({bid: 8, bname: "SE", Author: "Pressman",edition: 5})

"acknowledged" : true,

"insertedId" : ObjectId("6150a617f945783949c3ffb7")

Many records inserted at a time


db.book.insertMany([{bid: 9, bname: "os", Author: "Tanenbaum",edition: 5},{bid: 3,
bname:"dlda",Author: "rpJain",edition: 3}])

"acknowledged" : true,

"insertedIds" : [

ObjectId("6150a811f945783949c3ffb8"),

ObjectId("6150a811f945783949c3ffb9")

Update command:

db.book.updateOne({bname: "dlda"},{$set: {edition: 5}});

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

Ascending order:

> db.book.find().sort({bid: 1})

{ "_id" : ObjectId("6150a40ef945783949c3ffb6"), "bid" : 2, "bname" : "DBMS priciples", "Author" :


"korth", "edition" : 4 }

{ "_id" : ObjectId("6150a811f945783949c3ffb9"), "bid" : 3, "bname" : "dlda", "Author" : "rpJain",


"edition" : 3 }

{ "_id" : ObjectId("6150a1b2f945783949c3ffb5"), "bid" : 5, "bname" : "ADBMS priciples", "Author" :


"Navathe", "edition" : 4 }

{ "_id" : ObjectId("6150a617f945783949c3ffb7"), "bid" : 8, "bname" : "SE", "Author" : "Pressman",


"edition" : 5 }

{ "_id" : ObjectId("6150a811f945783949c3ffb8"), "bid" : 9, "bname" : "os", "Author" : "Tanenbaum",


"edition" : 5 }

Descending order

> db.book.find().sort({bid: -1})


{ "_id" : ObjectId("6150a811f945783949c3ffb8"), "bid" : 9, "bname" : "os", "Author" : "Tanenbaum",
"edition" : 5 }

{ "_id" : ObjectId("6150a617f945783949c3ffb7"), "bid" : 8, "bname" : "SE", "Author" : "Pressman",


"edition" : 5 }

{ "_id" : ObjectId("6150a1b2f945783949c3ffb5"), "bid" : 5, "bname" : "ADBMS priciples", "Author" :


"Navathe", "edition" : 4 }

{ "_id" : ObjectId("6150a811f945783949c3ffb9"), "bid" : 3, "bname" : "dlda", "Author" : "rpJain",


"edition" : 3 }

{ "_id" : ObjectId("6150a40ef945783949c3ffb6"), "bid" : 2, "bname" : "DBMS priciples", "Author" :


"korth", "edition" : 4 }

>

Display only two records

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

"_id" : ObjectId("6150a1b2f945783949c3ffb5"),

"bid" : 5,

"bname" : "ADBMS priciples",

"Author" : "Navathe",

"edition" : 4

"_id" : ObjectId("6150a40ef945783949c3ffb6"),

"bid" : 2,

"bname" : "DBMS priciples",

"Author" : "korth",

"edition" : 4
}

Display book whose edition are greater than 3

db.book.find({edition: {$gt:3}}).pretty()

"_id" : ObjectId("6150a1b2f945783949c3ffb5"),

"bid" : 5,

"bname" : "ADBMS priciples",

"Author" : "Navathe",

"edition" : 4

"_id" : ObjectId("6150a40ef945783949c3ffb6"),

"bid" : 2,

"bname" : "DBMS priciples",

"Author" : "korth",

"edition" : 4

"_id" : ObjectId("6150a617f945783949c3ffb7"),

"bid" : 8,

"bname" : "SE",

"Author" : "Pressman",

"edition" : 5

}
{

"_id" : ObjectId("6150a811f945783949c3ffb8"),

"bid" : 9,

"bname" : "os",

"Author" : "Tanenbaum",

"edition" : 5

And operator

db.book.find({$and: [{"Author":"korth"},{"edition": 4}]}).pretty()

"_id" : ObjectId("6150a40ef945783949c3ffb6"),

"bid" : 2,

"bname" : "DBMS priciples",

"Author" : "korth",

"edition" : 4

OR operator

db.book.find({$or: [{"Author":"korth"},{"Author":"Pressman"}]}).pretty()

"_id" : ObjectId("6150a40ef945783949c3ffb6"),

"bid" : 2,

"bname" : "DBMS priciples",

"Author" : "korth",

"edition" : 4

}
{

"_id" : ObjectId("6150a617f945783949c3ffb7"),

"bid" : 8,

"bname" : "SE",

"Author" : "Pressman",

"edition" : 5

Not less than equals 3

db.book.find({"edition": {$not: {$lte: 3}}}).pretty()

"_id" : ObjectId("6150a1b2f945783949c3ffb5"),

"bid" : 5,

"bname" : "ADBMS priciples",

"Author" : "Navathe",

"edition" : 4

"_id" : ObjectId("6150a40ef945783949c3ffb6"),

"bid" : 2,

"bname" : "DBMS priciples",

"Author" : "korth",

"edition" : 4

{
"_id" : ObjectId("6150a617f945783949c3ffb7"),

"bid" : 8,

"bname" : "SE",

"Author" : "Pressman",

"edition" : 5

"_id" : ObjectId("6150a811f945783949c3ffb8"),

"bid" : 9,

"bname" : "os",

"Author" : "Tanenbaum",

"edition" : 5

Remove all

db.student.remove({})

WriteResult({ "nRemoved" : 0 })

You might also like