SlideShare a Scribd company logo
Ms. Chitra Alavani
HoD Computer Science
Kaveri College of Arts, Science and Commerce
• Made up of Multiple Collections.
• Created on-the-fly when referenced for the first time.
The "use" command is used to create a database in MongoDB. If the database does not exist a
new one will be created.
Syntax:
• Schema-less, and contains Documents.
• Created on-the-fly when referenced for the first time.
• Capped Collections: Fixed size, older records get dropped after reaching the limit.
Syntax: db.createCollection(name, options)
Options parameter is optional, so you need to specify only the name of the collection
Name String Name of the collection to be created
Options Document (Optional) Specify options about memory size and
indexing
• Other way to create a collection is to insert a record (which is nothing but a document
consisting of Field names and Values) into a collection. If the collection does not exist a new
one will be created.
• Stored in a Collection.
• Can have _id key – works like Primary keys in MySQL.
• Supported Relationships – Embedded (or) References.
Creating a Document
• db.collection.insertOne() : Inserts a document into a collection.
• db.collection.insertMany() : Inserts multiple documents into a collection.
• db.collection.insert() : Inserts a document or documents into a collection.
Setting _id field
• MongoDB automatically add an Object id field which acts as a primary key
of the document.
• If you want to ensure that MongoDB does not create the _id Field when the
collection is created and if you want to specify your own id as the _id of the
collection, then you need to explicitly define this while creating the
collection.
db.Employee.insert({_id:10, "EmployeeName" : "Smith"})
Updating a Document
• db.collection.update (query, update, options): Modifies an existing document
or documents in a collection. The method can modify specific fields of an
existing document or documents or replace an existing document entirely,
depending on the update parameter.
db.employee.update({ename:"Kaveri"},{$set:{addr:"Pune"}});
Updating a Document
db.Movies.update({title:"Arrival"},{$set:{"stars": [
{
"name": "Amy Adams",
"birthYear": 1974,
"nationality": "American",
"wonOscar": false
}]}},{upsert:true})
With the upsert option set to true, if no matching documents exist, then the update operation
performs an insert.
Deleting a Document
• The MongoDB shell provides the following methods to delete documents
from a collection:
• To delete multiple documents, use db.collection.deleteMany().
• To delete a single document, use db.collection.deleteOne().
Deleting a Document
• remove() method can also be used to remove a document from the
collection. remove() method accepts two parameters. One is deletion criteria
and second is justOne flag.
db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)
• deletion criteria − (Optional) deletion criteria according to documents will be removed.
• justOne − (Optional) if set to true or 1, then remove only one document.
Dropping Collection
• db.collection.drop() is used to drop a collection from the database.
db.COLLECTION_NAME.drop()
Dropping Database
• db.dropDatabase() command is used to drop a existing database.
db.dropDatabase()
• This will delete the selected database. If you have not selected any database, then it will
delete default 'test' database.
>use mydb
switched to db mydb
>db.dropDatabase()
>{ "dropped" : "mydb", "ok" : 1 }
>
Querying a Collection
• db.collection.find (query, projection) : Selects documents in a collection or
view and returns a cursor to the selected documents.
• query : Optional. Specifies selection filter using query operators. To return all
documents in a collection, omit this parameter or pass an empty document
({}).
• projection: Optional. Specifies the fields to return in the documents that
match the query filter. To return all fields in the matching documents, omit
this parameter.
Querying a Collection
• MongoDB provides a function called db.collection.find () which is used for
retrieval of documents from a MongoDB database.
• To display the results in a formatted way, you can use pretty method.
db.Employee.find().pretty()
Querying a Collection
• Query to select movie having title = Arrival
db.Movies.find({title: “Arrival”}).pretty()
• Query to select movie according to the genre
db.Movies.find({"genre": "Sci-Fi"}).pretty()
Querying a Collection
• We can use the
following comparison
operators in our queries:
Querying a Collection
• Query to find movies released after 2000 and only get the title field using
the projection parameter
db.Movies.find({year: {$gt: 2000}}, {title: 1, _id: 0}).pretty()
• The _id field is always displayed by default. So we need to explicitly mention
_id:0
• Query to find movies released in or after 2014
db.Movies.find({"year": { $gte: 2014}}).pretty()
Querying a Collection
• We can also use logical operators in our queries.
Querying a Collection
• Query to find the movies which were released before 2000 and have
a budget greater than 50 million:.
db.Movies.find({$and:[{year: {$lt: 2000}}, {budget: {$gt:
50000000}}]}).pretty()
• Query to find if the movie of genre Sci-Fi and Drama
db.Movies.find({ $and: [{"genre": "Sci-Fi"}, {"genre": "Drama"}]}).pretty()
Querying a Collection
• Query to find the movies which were released after 2015 or were of the
genre Sci-Fi
db.Movies.find({$or:[{year: {$gt: 2015}}, {genre: “Sci-Fi” }]}).pretty()
• Find documents that do not match either of the following conditions. genre
is equal to “Mystery” or “Sci-Fi”
db.Movies.find({ $nor: [{"genre": "Mystery"}, {"genre": "Sci-Fi"}]}).pretty()
Querying a Collection
• We can use the element query operators to identify documents using the
fields of the document.
Operator Description
$exists Matches documents that have the specified field.
$type
Matches documents according to the specified field type. These field types
are specified BSON types and can be defined either by type number or alias.
Querying a Collection
• Find documents where the budget field exists
db.Movies.find({ "budget": { $exists: true}}).pretty()
• Query will return document if the budget field is a double type
db.Movies.find({ "budget": { $type: "double"}}).pretty()
How to Limit, Skip and Sort Records
• The limit () Method
• Used to limit the number of documents to be displayed.
• This argument is an optional field inside the ‘limit ()’ method, and when not
specified then by default, it will display all the documents from the collection.
db.COLLECTION_NAME.find().limit(NUMBER)
How to Limit, Skip and Sort Records
• The skip () Method
• Used to skip the number of documents. Like the ‘limit ()’ method, it accepts
only one argument which is of number type. Depending on the value of the
number, we can skip the number of documents to be displayed.
• This argument is an optional field inside the ‘skip ()’ method, and when not
specified, then it will display all documents from the collection as the default
value in ‘skip ()’ method is 0.
db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)
How to Limit, Skip and Sort Records
• The sort () Method
• Used to sort the documents inside a collection. It accepts a document which contains a
list of fields along with their sorting order.
• 1 and -1 is used in order to specify the sorting order where 1 corresponds to the
ascending order and -1 corresponds to the descending order.
• Default sorting order is ascending order.
db.COLLECTION_NAME.find().sort({KEY:1})
db.Movies.find({},{"stars.birthYear":1,_id:0}).sort({"stars.birthYear": 1})
Cursor
• When the db.collection.find () function is used to search for documents in
the collection, the result returns a pointer to the collection of documents
returned which is called a cursor.
• By default, the cursor will be iterated automatically when the result of the
query is returned. But one can also explicitly go through the items returned
in the cursor one by one.
Cursor
var myMovie = db.Movies.find( { year : { $gt:2015 }});
while(myMovie.hasNext()){
print(tojson(myMovie.next()));
}
Aggregation
• Most often queries in mongodb are just to do CRUD(Create Read Update
and Delete) operations.
• But, when an application gets more complex, you may need to perform
several operations on the data before sending it as a response
• Here comes the role of MongoDB Aggregation
MongoDB Aggregation Pipeline
pipeline = [
{ $match : { … },
{ $group : { … },
{ $sort : { … },
... ]
db.collectionName.aggregate(pipeline, options)
MongoDB Aggregation Pipeline
• $match
• match operator is similar to find() operator in mongoDB except that match works with aggregation.
Likewise, match pipeline operator matches all the documents that satisfies the condition.
• Match all the documents which has MA as a state.
db.aggresample.aggregate([ {
$match: {
state: "MA",
}, }, ]).pretty()
MongoDB Aggregation Pipeline
• $group
• As the name suggests, it groups the documents based on the particular field. it can be id or
any other fields.
db.aggresample.aggregate([ {
$match: {
state: "ME",
}, },
{
$group :{
_id:"$state",
population: { $avg: "$pop" }
}, }, ]).pretty()
MongoDB Aggregation Pipeline
db.aggresample.aggregate([
{
$group: {
_id: null,
total: { $sum: "$pop“ },
average_population: { $avg: "$pop“ },
min_population: { $min: "$pop“ },
max_population: { $max: "$pop“ }
}
}
]);
MongoDB Aggregation Pipeline
• $project
• Sometimes, you may not need all the fields in the document. you can only retrieve specific fields in the document
using project operator
db.aggresample.aggregate([ {
$match: {
state: "ME",
},
},
{
$project:{
_id:0, loc:1,
}, }, ]).pretty()
MongoDB Aggregation Pipeline
• $sort
• sort operator basically sorts the document in either ascending or descending order.
db.aggresample.aggregate([
{
$sort:{
pop:1,
},
},
]).pretty()
MongoDB Aggregation Pipeline
• $limit
• limit operator limits the number of documents retrieved from the database.
db.aggresample.aggregate([{
$sort:{
pop:-1,
},
},
{
$limit :5,
}, ]).pretty()
MongoDB Aggregation Pipeline
• $unwind
• You cannot work directly on the elements of an array within a document with
stages such as $group().
• The $unwind() stage enables us to work with the values of the fields within an array.
• Where there is an array field within the input documents, you will sometimes need
to output the document several times, once for every element of that array.
• Each copy of the document has the array field replaced with the successive element.
MongoDB Aggregation Pipeline
• $unwind
db.universities.aggregate([
{ $match : { name : 'USAL' } },
{ $unwind : '$students' }
]).pretty()
MongoDB Aggregation Pipeline
• get the total number of students that have ever belonged to each one of the
universities?
db.universities.aggregate([
{ $unwind : '$students' },
{ $group : { _id : '$name', totalalumni : { $sum : '$students.number'
} } }
]).pretty()
Lookup in Aggregation
• $lookup
• lookup is one of the popular
aggregation operators in
mongodb. Equivalent to
JOIN Query in RDBMS.
{
$lookup:
{
from: <collection to join>,
localField: <field from the input documents>,
foreignField: <field from the documents of the "from"
collection>,
as: <output array field>
}
}
Lookup in Aggregation
• $lookup
• lookup is one of the popular
aggregation operators in
mongodb. Equivalent to
JOIN Query in RDBMS.
{
$lookup:
{
from: <collection to join>,
localField: <field from the input documents>,
foreignField: <field from the documents of the "from"
collection>,
as: <output array field>
}
}
Lookup in Aggregation
db.universities.aggregate([
{ $match : { name : 'USAL' } },
{ $project : { _id : 0, name : 1 } },
{ $lookup : {
from : 'courses',
localField : 'name',
foreignField : 'university',
as : 'courses'
} }
]).pretty()
Slips

More Related Content

What's hot (20)

PPTX
Design pattern (Abstract Factory & Singleton)
paramisoft
 
PPTX
Dynamic method dispatch
yugandhar vadlamudi
 
PPTX
Color Models
Mustafa Salam
 
PPS
Java rmi
kamal kotecha
 
PPTX
Query processing and optimization (updated)
Ravinder Kamboj
 
PPTX
Deadlock dbms
Vardhil Patel
 
PPTX
trigger dbms
kuldeep100
 
PPTX
Constructors and Destructor in C++
International Institute of Information Technology (I²IT)
 
PDF
Domain Driven Design Made Functional with Python
Jean Carlo Machado
 
PPT
Java Collections Framework
Sony India Software Center
 
PPTX
List in Python
Siddique Ibrahim
 
PPTX
Ado.Net Tutorial
prabhu rajendran
 
PPTX
Dbms
Rupali Salunkhe
 
PPT
File organization 1
Rupali Rana
 
PPTX
Java - Generic programming
Riccardo Cardin
 
PDF
Android resource
Krazy Koder
 
PPT
SQLITE Android
Sourabh Sahu
 
PPTX
Introduction to Node.js
Vikash Singh
 
Design pattern (Abstract Factory & Singleton)
paramisoft
 
Dynamic method dispatch
yugandhar vadlamudi
 
Color Models
Mustafa Salam
 
Java rmi
kamal kotecha
 
Query processing and optimization (updated)
Ravinder Kamboj
 
Deadlock dbms
Vardhil Patel
 
trigger dbms
kuldeep100
 
Domain Driven Design Made Functional with Python
Jean Carlo Machado
 
Java Collections Framework
Sony India Software Center
 
List in Python
Siddique Ibrahim
 
Ado.Net Tutorial
prabhu rajendran
 
File organization 1
Rupali Rana
 
Java - Generic programming
Riccardo Cardin
 
Android resource
Krazy Koder
 
SQLITE Android
Sourabh Sahu
 
Introduction to Node.js
Vikash Singh
 

Similar to Mongo db queries (20)

PPTX
Introduction to MongoDB – A NoSQL Database
manikgupta2k04
 
PPTX
Introduction to MongoDB
S.Shayan Daneshvar
 
PPTX
Mongo Nosql CRUD Operations
anujaggarwal49
 
PPTX
mongo.pptx
tarungupta276841
 
PPTX
Mongo db
Ramakrishna kapa
 
PPTX
Getting Started with MongoDB
Ahasanul Kalam Akib
 
PDF
Mongo db basics
Harischandra M K
 
PPTX
Mongo DB Presentation
Jaya Naresh Kovela
 
PPTX
fard car.pptx
tarungupta276841
 
PPS
MongoDB crud
Darshan Jayarama
 
PPTX
MongoDB - An Introduction
dinkar thakur
 
PPTX
Mongo DB 102
Abhijeet Vaikar
 
PPTX
MongoDB-presentation.pptx
tarungupta276841
 
PPTX
MongoDB_ppt.pptx
1AP18CS037ShirishKul
 
PDF
MongoDB.pdf54teeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeer
MdRiyad22
 
PPT
Mongo db basics
Dhaval Mistry
 
PPTX
MongoDB installation,CRUD operation & JavaScript shell
ShahDhruv21
 
PPTX
Introduction To MongoDB
ElieHannouch
 
PPTX
Mongo db basic installation
Kishor Parkhe
 
PPT
MongoDB
kesavan N B
 
Introduction to MongoDB – A NoSQL Database
manikgupta2k04
 
Introduction to MongoDB
S.Shayan Daneshvar
 
Mongo Nosql CRUD Operations
anujaggarwal49
 
mongo.pptx
tarungupta276841
 
Getting Started with MongoDB
Ahasanul Kalam Akib
 
Mongo db basics
Harischandra M K
 
Mongo DB Presentation
Jaya Naresh Kovela
 
fard car.pptx
tarungupta276841
 
MongoDB crud
Darshan Jayarama
 
MongoDB - An Introduction
dinkar thakur
 
Mongo DB 102
Abhijeet Vaikar
 
MongoDB-presentation.pptx
tarungupta276841
 
MongoDB_ppt.pptx
1AP18CS037ShirishKul
 
MongoDB.pdf54teeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeer
MdRiyad22
 
Mongo db basics
Dhaval Mistry
 
MongoDB installation,CRUD operation & JavaScript shell
ShahDhruv21
 
Introduction To MongoDB
ElieHannouch
 
Mongo db basic installation
Kishor Parkhe
 
MongoDB
kesavan N B
 
Ad

Recently uploaded (20)

DOCX
Lesson 1 - Nature and Inquiry of Research
marvinnbustamante1
 
PPTX
DAY 1_QUARTER1 ENGLISH 5 WEEK- PRESENTATION.pptx
BanyMacalintal
 
PDF
Week 2 - Irish Natural Heritage Powerpoint.pdf
swainealan
 
PDF
Vani - The Voice of Excellence - Jul 2025 issue
Savipriya Raghavendra
 
PPTX
Light Reflection and Refraction- Activities - Class X Science
SONU ACADEMY
 
PPTX
Introduction to Indian Writing in English
Trushali Dodiya
 
PPTX
Introduction to Biochemistry & Cellular Foundations.pptx
marvinnbustamante1
 
PPTX
PLANNING FOR EMERGENCY AND DISASTER MANAGEMENT ppt.pptx
PRADEEP ABOTHU
 
PPTX
AIMA UCSC-SV Leadership_in_the_AI_era 20250628 v16.pptx
home
 
PPTX
DIGITAL CITIZENSHIP TOPIC TLE 8 MATATAG CURRICULUM
ROBERTAUGUSTINEFRANC
 
PDF
Is Assignment Help Legal in Australia_.pdf
thomas19williams83
 
PDF
I3PM Industry Case Study Siemens on Strategic and Value-Oriented IP Management
MIPLM
 
PPTX
Marketing Management PPT Unit 1 and Unit 2.pptx
Sri Ramakrishna College of Arts and science
 
PPTX
How to Manage Expiry Date in Odoo 18 Inventory
Celine George
 
PPTX
Lesson 1 Cell (Structures, Functions, and Theory).pptx
marvinnbustamante1
 
PDF
WATERSHED MANAGEMENT CASE STUDIES - ULUGURU MOUNTAINS AND ARVARI RIVERpdf
Ar.Asna
 
PDF
I3PM Case study smart parking 2025 with uptoIP® and ABP
MIPLM
 
PDF
Governor Josh Stein letter to NC delegation of U.S. House
Mebane Rash
 
PPTX
infertility, types,causes, impact, and management
Ritu480198
 
PPTX
How to Configure Re-Ordering From Portal in Odoo 18 Website
Celine George
 
Lesson 1 - Nature and Inquiry of Research
marvinnbustamante1
 
DAY 1_QUARTER1 ENGLISH 5 WEEK- PRESENTATION.pptx
BanyMacalintal
 
Week 2 - Irish Natural Heritage Powerpoint.pdf
swainealan
 
Vani - The Voice of Excellence - Jul 2025 issue
Savipriya Raghavendra
 
Light Reflection and Refraction- Activities - Class X Science
SONU ACADEMY
 
Introduction to Indian Writing in English
Trushali Dodiya
 
Introduction to Biochemistry & Cellular Foundations.pptx
marvinnbustamante1
 
PLANNING FOR EMERGENCY AND DISASTER MANAGEMENT ppt.pptx
PRADEEP ABOTHU
 
AIMA UCSC-SV Leadership_in_the_AI_era 20250628 v16.pptx
home
 
DIGITAL CITIZENSHIP TOPIC TLE 8 MATATAG CURRICULUM
ROBERTAUGUSTINEFRANC
 
Is Assignment Help Legal in Australia_.pdf
thomas19williams83
 
I3PM Industry Case Study Siemens on Strategic and Value-Oriented IP Management
MIPLM
 
Marketing Management PPT Unit 1 and Unit 2.pptx
Sri Ramakrishna College of Arts and science
 
How to Manage Expiry Date in Odoo 18 Inventory
Celine George
 
Lesson 1 Cell (Structures, Functions, and Theory).pptx
marvinnbustamante1
 
WATERSHED MANAGEMENT CASE STUDIES - ULUGURU MOUNTAINS AND ARVARI RIVERpdf
Ar.Asna
 
I3PM Case study smart parking 2025 with uptoIP® and ABP
MIPLM
 
Governor Josh Stein letter to NC delegation of U.S. House
Mebane Rash
 
infertility, types,causes, impact, and management
Ritu480198
 
How to Configure Re-Ordering From Portal in Odoo 18 Website
Celine George
 
Ad

Mongo db queries

  • 1. Ms. Chitra Alavani HoD Computer Science Kaveri College of Arts, Science and Commerce
  • 2. • Made up of Multiple Collections. • Created on-the-fly when referenced for the first time. The "use" command is used to create a database in MongoDB. If the database does not exist a new one will be created. Syntax:
  • 3. • Schema-less, and contains Documents. • Created on-the-fly when referenced for the first time. • Capped Collections: Fixed size, older records get dropped after reaching the limit. Syntax: db.createCollection(name, options) Options parameter is optional, so you need to specify only the name of the collection Name String Name of the collection to be created Options Document (Optional) Specify options about memory size and indexing
  • 4. • Other way to create a collection is to insert a record (which is nothing but a document consisting of Field names and Values) into a collection. If the collection does not exist a new one will be created.
  • 5. • Stored in a Collection. • Can have _id key – works like Primary keys in MySQL. • Supported Relationships – Embedded (or) References.
  • 6. Creating a Document • db.collection.insertOne() : Inserts a document into a collection. • db.collection.insertMany() : Inserts multiple documents into a collection. • db.collection.insert() : Inserts a document or documents into a collection.
  • 7. Setting _id field • MongoDB automatically add an Object id field which acts as a primary key of the document. • If you want to ensure that MongoDB does not create the _id Field when the collection is created and if you want to specify your own id as the _id of the collection, then you need to explicitly define this while creating the collection. db.Employee.insert({_id:10, "EmployeeName" : "Smith"})
  • 8. Updating a Document • db.collection.update (query, update, options): Modifies an existing document or documents in a collection. The method can modify specific fields of an existing document or documents or replace an existing document entirely, depending on the update parameter. db.employee.update({ename:"Kaveri"},{$set:{addr:"Pune"}});
  • 9. Updating a Document db.Movies.update({title:"Arrival"},{$set:{"stars": [ { "name": "Amy Adams", "birthYear": 1974, "nationality": "American", "wonOscar": false }]}},{upsert:true}) With the upsert option set to true, if no matching documents exist, then the update operation performs an insert.
  • 10. Deleting a Document • The MongoDB shell provides the following methods to delete documents from a collection: • To delete multiple documents, use db.collection.deleteMany(). • To delete a single document, use db.collection.deleteOne().
  • 11. Deleting a Document • remove() method can also be used to remove a document from the collection. remove() method accepts two parameters. One is deletion criteria and second is justOne flag. db.COLLECTION_NAME.remove(DELLETION_CRITTERIA) • deletion criteria − (Optional) deletion criteria according to documents will be removed. • justOne − (Optional) if set to true or 1, then remove only one document.
  • 12. Dropping Collection • db.collection.drop() is used to drop a collection from the database. db.COLLECTION_NAME.drop()
  • 13. Dropping Database • db.dropDatabase() command is used to drop a existing database. db.dropDatabase() • This will delete the selected database. If you have not selected any database, then it will delete default 'test' database. >use mydb switched to db mydb >db.dropDatabase() >{ "dropped" : "mydb", "ok" : 1 } >
  • 14. Querying a Collection • db.collection.find (query, projection) : Selects documents in a collection or view and returns a cursor to the selected documents. • query : Optional. Specifies selection filter using query operators. To return all documents in a collection, omit this parameter or pass an empty document ({}). • projection: Optional. Specifies the fields to return in the documents that match the query filter. To return all fields in the matching documents, omit this parameter.
  • 15. Querying a Collection • MongoDB provides a function called db.collection.find () which is used for retrieval of documents from a MongoDB database. • To display the results in a formatted way, you can use pretty method. db.Employee.find().pretty()
  • 16. Querying a Collection • Query to select movie having title = Arrival db.Movies.find({title: “Arrival”}).pretty() • Query to select movie according to the genre db.Movies.find({"genre": "Sci-Fi"}).pretty()
  • 17. Querying a Collection • We can use the following comparison operators in our queries:
  • 18. Querying a Collection • Query to find movies released after 2000 and only get the title field using the projection parameter db.Movies.find({year: {$gt: 2000}}, {title: 1, _id: 0}).pretty() • The _id field is always displayed by default. So we need to explicitly mention _id:0 • Query to find movies released in or after 2014 db.Movies.find({"year": { $gte: 2014}}).pretty()
  • 19. Querying a Collection • We can also use logical operators in our queries.
  • 20. Querying a Collection • Query to find the movies which were released before 2000 and have a budget greater than 50 million:. db.Movies.find({$and:[{year: {$lt: 2000}}, {budget: {$gt: 50000000}}]}).pretty() • Query to find if the movie of genre Sci-Fi and Drama db.Movies.find({ $and: [{"genre": "Sci-Fi"}, {"genre": "Drama"}]}).pretty()
  • 21. Querying a Collection • Query to find the movies which were released after 2015 or were of the genre Sci-Fi db.Movies.find({$or:[{year: {$gt: 2015}}, {genre: “Sci-Fi” }]}).pretty() • Find documents that do not match either of the following conditions. genre is equal to “Mystery” or “Sci-Fi” db.Movies.find({ $nor: [{"genre": "Mystery"}, {"genre": "Sci-Fi"}]}).pretty()
  • 22. Querying a Collection • We can use the element query operators to identify documents using the fields of the document. Operator Description $exists Matches documents that have the specified field. $type Matches documents according to the specified field type. These field types are specified BSON types and can be defined either by type number or alias.
  • 23. Querying a Collection • Find documents where the budget field exists db.Movies.find({ "budget": { $exists: true}}).pretty() • Query will return document if the budget field is a double type db.Movies.find({ "budget": { $type: "double"}}).pretty()
  • 24. How to Limit, Skip and Sort Records • The limit () Method • Used to limit the number of documents to be displayed. • This argument is an optional field inside the ‘limit ()’ method, and when not specified then by default, it will display all the documents from the collection. db.COLLECTION_NAME.find().limit(NUMBER)
  • 25. How to Limit, Skip and Sort Records • The skip () Method • Used to skip the number of documents. Like the ‘limit ()’ method, it accepts only one argument which is of number type. Depending on the value of the number, we can skip the number of documents to be displayed. • This argument is an optional field inside the ‘skip ()’ method, and when not specified, then it will display all documents from the collection as the default value in ‘skip ()’ method is 0. db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)
  • 26. How to Limit, Skip and Sort Records • The sort () Method • Used to sort the documents inside a collection. It accepts a document which contains a list of fields along with their sorting order. • 1 and -1 is used in order to specify the sorting order where 1 corresponds to the ascending order and -1 corresponds to the descending order. • Default sorting order is ascending order. db.COLLECTION_NAME.find().sort({KEY:1}) db.Movies.find({},{"stars.birthYear":1,_id:0}).sort({"stars.birthYear": 1})
  • 27. Cursor • When the db.collection.find () function is used to search for documents in the collection, the result returns a pointer to the collection of documents returned which is called a cursor. • By default, the cursor will be iterated automatically when the result of the query is returned. But one can also explicitly go through the items returned in the cursor one by one.
  • 28. Cursor var myMovie = db.Movies.find( { year : { $gt:2015 }}); while(myMovie.hasNext()){ print(tojson(myMovie.next())); }
  • 29. Aggregation • Most often queries in mongodb are just to do CRUD(Create Read Update and Delete) operations. • But, when an application gets more complex, you may need to perform several operations on the data before sending it as a response • Here comes the role of MongoDB Aggregation
  • 30. MongoDB Aggregation Pipeline pipeline = [ { $match : { … }, { $group : { … }, { $sort : { … }, ... ] db.collectionName.aggregate(pipeline, options)
  • 31. MongoDB Aggregation Pipeline • $match • match operator is similar to find() operator in mongoDB except that match works with aggregation. Likewise, match pipeline operator matches all the documents that satisfies the condition. • Match all the documents which has MA as a state. db.aggresample.aggregate([ { $match: { state: "MA", }, }, ]).pretty()
  • 32. MongoDB Aggregation Pipeline • $group • As the name suggests, it groups the documents based on the particular field. it can be id or any other fields. db.aggresample.aggregate([ { $match: { state: "ME", }, }, { $group :{ _id:"$state", population: { $avg: "$pop" } }, }, ]).pretty()
  • 33. MongoDB Aggregation Pipeline db.aggresample.aggregate([ { $group: { _id: null, total: { $sum: "$pop“ }, average_population: { $avg: "$pop“ }, min_population: { $min: "$pop“ }, max_population: { $max: "$pop“ } } } ]);
  • 34. MongoDB Aggregation Pipeline • $project • Sometimes, you may not need all the fields in the document. you can only retrieve specific fields in the document using project operator db.aggresample.aggregate([ { $match: { state: "ME", }, }, { $project:{ _id:0, loc:1, }, }, ]).pretty()
  • 35. MongoDB Aggregation Pipeline • $sort • sort operator basically sorts the document in either ascending or descending order. db.aggresample.aggregate([ { $sort:{ pop:1, }, }, ]).pretty()
  • 36. MongoDB Aggregation Pipeline • $limit • limit operator limits the number of documents retrieved from the database. db.aggresample.aggregate([{ $sort:{ pop:-1, }, }, { $limit :5, }, ]).pretty()
  • 37. MongoDB Aggregation Pipeline • $unwind • You cannot work directly on the elements of an array within a document with stages such as $group(). • The $unwind() stage enables us to work with the values of the fields within an array. • Where there is an array field within the input documents, you will sometimes need to output the document several times, once for every element of that array. • Each copy of the document has the array field replaced with the successive element.
  • 38. MongoDB Aggregation Pipeline • $unwind db.universities.aggregate([ { $match : { name : 'USAL' } }, { $unwind : '$students' } ]).pretty()
  • 39. MongoDB Aggregation Pipeline • get the total number of students that have ever belonged to each one of the universities? db.universities.aggregate([ { $unwind : '$students' }, { $group : { _id : '$name', totalalumni : { $sum : '$students.number' } } } ]).pretty()
  • 40. Lookup in Aggregation • $lookup • lookup is one of the popular aggregation operators in mongodb. Equivalent to JOIN Query in RDBMS. { $lookup: { from: <collection to join>, localField: <field from the input documents>, foreignField: <field from the documents of the "from" collection>, as: <output array field> } }
  • 41. Lookup in Aggregation • $lookup • lookup is one of the popular aggregation operators in mongodb. Equivalent to JOIN Query in RDBMS. { $lookup: { from: <collection to join>, localField: <field from the input documents>, foreignField: <field from the documents of the "from" collection>, as: <output array field> } }
  • 42. Lookup in Aggregation db.universities.aggregate([ { $match : { name : 'USAL' } }, { $project : { _id : 0, name : 1 } }, { $lookup : { from : 'courses', localField : 'name', foreignField : 'university', as : 'courses' } } ]).pretty()
  • 43. Slips