SlideShare ist ein Scribd-Unternehmen logo
1 von 15
Query & Aggregation on MongoDB
26 March 2012
Agenda
 About
 Remember: CRUD
 Querying
 Indexes
 Aggregation
 QA
About
 Who Am I?
{
"Name": "Bogdan Sabau",
“Position": "SQL Developer",
"Project": "lynda.com",
"Why": [
"Big Data",
"NoSQL",
"Open Source"
]
}
About
 Who Am I?
{
"Name": "Bogdan Sabau",
“Position": "SQL Developer",
"Project": "lynda.com",
"Why": [
"Big Data",
"NoSQL",
"Open Source"
]
}
Remember: CRUD
 CREATE new record:
 db.zips.insert({"city": "OINKTOWN", "loc": [-89.51557, 32.584132], "pop": 789, "state": "AL"})
 READ a record:
 db.zips.find({"city": "OINKTOWN"})
 UPDATE existing record:
 db.zips.update({"city": "OINKTOWN"}, {"city": "OINKTOWN", "loc": [-89.51557, 32.584132], "pop":
1000, "state": "AL"})
 db.zips.update({"_id": "999"}, { $set: {"pop":2000}})
 db.zips.update({"_id": "999"}, { $set: {"greencity":true}})
 DELETE a record:
 db.zips.remove({"_id": "999"})
Querying
 Adhoc queries using find() or findOne() functions
 You can query for ranges, set inclusion, inequalities, and more by using $
conditionals.
 For more complex queries you can use $where clause
 All queries return a cursor
 You can make operations on that specific cursor
Querying
 Simple examples:
 db.zips.find({"state": "AL"})
 db.zibs.find({"state": "AL"}, {"city":1, "pop":1})
 Using "$lt", "$lte", "$gt", "$gte“, "$in", "$or", "$eq", "$not":
 db.zips.find({"state": "AL", "pop": {"$lt": 500}}, {"loc":0})
 db.zips.find({"state": {"$in": ["AL", "NY"]}, "pop": {"$lt": 50}})
 db.zips.find({"$or": [{"pop": {"$lt": 1}}, {"city": "NEW YORK"}]}, {"city":1, "state":1, "pop":1})
 NULL match itself but also match a key that doesn’t exists
 We can use regular expressions: db.zips.find({"city": /new .*/i})
 We can query arrays and embedded documents
Querying
 $Where queries:
 Used when we are dealing with more complex queries
 Are using JavaScript
 Slower than regular queries because they convert every BSON object to a JavaScript object
 Example
 db.zips.insert({"_id":"2", "city":"Alba", "county":"Alba", "country":"Romania", "museums": ["Muzeul de
Istorie", "Muzeul Unirii"]})
 db.zips.find({$where: function() { return this.city == this.county }})
 Cursors
 Used same as on SQL; we can limit the results, fetch the results and apply JavaScript logic on them
Indexes
 MongoDB’s indexes work almost identically to typical relational database
indexes
 Using a query optimizer to find the best index
 We can create indexes on embedded documents
 Unique indexes are possible
 Compound unique indexes
 Geospatial indexes
Indexes
 db.collection.find().explain() – give us information about indexes
 db.collection.ensureIndex({“key”:<order>}) – create a new index
 db.system.indexes.find() – check all the indexes
 db.collection.dropIndex (“indexname”) – drop the index
 There is another type of query that is becoming increasingly common
(especially with the emergence of mobile devices): finding the nearest N
things to a current location. MongoDB provides a special type of index for
coordinate plane queries, called a geospatial index.
Aggregation
 Count: returns the number of documents from the collection
 Sum: returns the sum of all the values for a specified field in the grouped
document
 Distinct: find the distinctive values for a specific key
 Group allows you to perform more complex aggregation. You choose a key
to group by, and MongoDB divides the collection into separate groups for
each value of the chosen key. For each group, you can create a result
document by aggregating the documents that are members of that group.
Aggregation
 Count
 db.zips.count()
 db.zips.count({"state":"NY"})
 Distinct
 db.runCommand({"distinct" : "zips", "key" : "state"})
 Group: SQL equivlants:
 WHERE $match GROUP BY $group
 HAVING $match SELECT $project
 ORDER BY $sort LIMIT $limit
 SUM() $sum COUNT() $sum
Aggregation
 Group examples
 Population by State
db.zips.aggregate( { $group :
{ _id : "$state",
totalPop : { $sum : "$pop" } } })
 Population by State with condition
db.zips.aggregate( { $group :
{ _id : "$state",
totalPop : { $sum : "$pop" } } },
{ $match : {totalPop : { $gte : 10*1000*1000 } } }
Aggregation
 Group examples
 Largest and smallest cities by State
db.zips.aggregate( { $group:
{ _id: { state: "$state", city: "$city" },
pop: { $sum: "$pop" } } },
{ $sort: { pop: 1 } },
{ $group:
{ _id : "$_id.state",
biggestCity: { $last: "$_id.city" },
biggestPop: { $last: "$pop" },
smallestCity: { $first: "$_id.city" },
smallestPop: { $first: "$pop" } } })
QA

Weitere ähnliche Inhalte

Was ist angesagt?

The Aggregation Framework
The Aggregation FrameworkThe Aggregation Framework
The Aggregation Framework
MongoDB
 
CouchDB Open Source Bridge
CouchDB Open Source BridgeCouchDB Open Source Bridge
CouchDB Open Source Bridge
Chris Anderson
 

Was ist angesagt? (20)

Mongo DB 102
Mongo DB 102Mongo DB 102
Mongo DB 102
 
Agg framework selectgroup feb2015 v2
Agg framework selectgroup feb2015 v2Agg framework selectgroup feb2015 v2
Agg framework selectgroup feb2015 v2
 
Mongo Presentation by Metatagg Solutions
Mongo Presentation by Metatagg SolutionsMongo Presentation by Metatagg Solutions
Mongo Presentation by Metatagg Solutions
 
PhpstudyTokyo MongoDB PHP CakePHP
PhpstudyTokyo MongoDB PHP CakePHPPhpstudyTokyo MongoDB PHP CakePHP
PhpstudyTokyo MongoDB PHP CakePHP
 
The Aggregation Framework
The Aggregation FrameworkThe Aggregation Framework
The Aggregation Framework
 
CouchDB Open Source Bridge
CouchDB Open Source BridgeCouchDB Open Source Bridge
CouchDB Open Source Bridge
 
Back to Basics Webinar 3: Schema Design Thinking in Documents
 Back to Basics Webinar 3: Schema Design Thinking in Documents Back to Basics Webinar 3: Schema Design Thinking in Documents
Back to Basics Webinar 3: Schema Design Thinking in Documents
 
MongoDB for Analytics
MongoDB for AnalyticsMongoDB for Analytics
MongoDB for Analytics
 
Webinar: Exploring the Aggregation Framework
Webinar: Exploring the Aggregation FrameworkWebinar: Exploring the Aggregation Framework
Webinar: Exploring the Aggregation Framework
 
Dev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBDev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDB
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
MongoDB - javascript for your data
MongoDB - javascript for your dataMongoDB - javascript for your data
MongoDB - javascript for your data
 
Webinar: Back to Basics: Thinking in Documents
Webinar: Back to Basics: Thinking in DocumentsWebinar: Back to Basics: Thinking in Documents
Webinar: Back to Basics: Thinking in Documents
 
Back to Basics Webinar 2: Your First MongoDB Application
Back to Basics Webinar 2: Your First MongoDB ApplicationBack to Basics Webinar 2: Your First MongoDB Application
Back to Basics Webinar 2: Your First MongoDB Application
 
Analytics with MongoDB Aggregation Framework and Hadoop Connector
Analytics with MongoDB Aggregation Framework and Hadoop ConnectorAnalytics with MongoDB Aggregation Framework and Hadoop Connector
Analytics with MongoDB Aggregation Framework and Hadoop Connector
 
Mondodb
MondodbMondodb
Mondodb
 
MongoDB at GUL
MongoDB at GULMongoDB at GUL
MongoDB at GUL
 
MongoDB
MongoDBMongoDB
MongoDB
 
Introduction to MongoDB at IGDTUW
Introduction to MongoDB at IGDTUWIntroduction to MongoDB at IGDTUW
Introduction to MongoDB at IGDTUW
 
Introduction to MongoDB for C# developers
Introduction to MongoDB for C# developersIntroduction to MongoDB for C# developers
Introduction to MongoDB for C# developers
 

Andere mochten auch (7)

Phplx mongodb
Phplx mongodbPhplx mongodb
Phplx mongodb
 
Indexing In MongoDB
Indexing In MongoDBIndexing In MongoDB
Indexing In MongoDB
 
Mongo indexes
Mongo indexesMongo indexes
Mongo indexes
 
NewSQL: The Best of Both "OldSQL" and "NoSQL"
NewSQL: The Best of Both "OldSQL" and "NoSQL"NewSQL: The Best of Both "OldSQL" and "NoSQL"
NewSQL: The Best of Both "OldSQL" and "NoSQL"
 
NewSQL
NewSQLNewSQL
NewSQL
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
Intro To MongoDB
Intro To MongoDBIntro To MongoDB
Intro To MongoDB
 

Ähnlich wie Querying mongo db

Aggregation in MongoDB
Aggregation in MongoDBAggregation in MongoDB
Aggregation in MongoDB
Kishor Parkhe
 
10gen Presents Schema Design and Data Modeling
10gen Presents Schema Design and Data Modeling10gen Presents Schema Design and Data Modeling
10gen Presents Schema Design and Data Modeling
DATAVERSITY
 
1403 app dev series - session 5 - analytics
1403   app dev series - session 5 - analytics1403   app dev series - session 5 - analytics
1403 app dev series - session 5 - analytics
MongoDB
 

Ähnlich wie Querying mongo db (20)

MongoDB Aggregations Indexing and Profiling
MongoDB Aggregations Indexing and ProfilingMongoDB Aggregations Indexing and Profiling
MongoDB Aggregations Indexing and Profiling
 
MongoDB Aggregation Framework
MongoDB Aggregation FrameworkMongoDB Aggregation Framework
MongoDB Aggregation Framework
 
Webinar: General Technical Overview of MongoDB for Dev Teams
Webinar: General Technical Overview of MongoDB for Dev TeamsWebinar: General Technical Overview of MongoDB for Dev Teams
Webinar: General Technical Overview of MongoDB for Dev Teams
 
Introduction to MongoDB and Workshop
Introduction to MongoDB and WorkshopIntroduction to MongoDB and Workshop
Introduction to MongoDB and Workshop
 
Starting with MongoDB
Starting with MongoDBStarting with MongoDB
Starting with MongoDB
 
Query for json databases
Query for json databasesQuery for json databases
Query for json databases
 
MongoDB.local DC 2018: Tutorial - Data Analytics with MongoDB
MongoDB.local DC 2018: Tutorial - Data Analytics with MongoDBMongoDB.local DC 2018: Tutorial - Data Analytics with MongoDB
MongoDB.local DC 2018: Tutorial - Data Analytics with MongoDB
 
Aggregation in MongoDB
Aggregation in MongoDBAggregation in MongoDB
Aggregation in MongoDB
 
Webinar: Applikationsentwicklung mit MongoDB : Teil 5: Reporting & Aggregation
Webinar: Applikationsentwicklung mit MongoDB: Teil 5: Reporting & AggregationWebinar: Applikationsentwicklung mit MongoDB: Teil 5: Reporting & Aggregation
Webinar: Applikationsentwicklung mit MongoDB : Teil 5: Reporting & Aggregation
 
MongoDB Meetup
MongoDB MeetupMongoDB Meetup
MongoDB Meetup
 
Data Analytics with MongoDB - Jane Fine
Data Analytics with MongoDB - Jane FineData Analytics with MongoDB - Jane Fine
Data Analytics with MongoDB - Jane Fine
 
10gen Presents Schema Design and Data Modeling
10gen Presents Schema Design and Data Modeling10gen Presents Schema Design and Data Modeling
10gen Presents Schema Design and Data Modeling
 
Back to Basics Webinar 4: Advanced Indexing, Text and Geospatial Indexes
Back to Basics Webinar 4: Advanced Indexing, Text and Geospatial IndexesBack to Basics Webinar 4: Advanced Indexing, Text and Geospatial Indexes
Back to Basics Webinar 4: Advanced Indexing, Text and Geospatial Indexes
 
2016 feb-23 pyugre-py_mongo
2016 feb-23 pyugre-py_mongo2016 feb-23 pyugre-py_mongo
2016 feb-23 pyugre-py_mongo
 
Using MongoDB and Python
Using MongoDB and PythonUsing MongoDB and Python
Using MongoDB and Python
 
Joins and Other Aggregation Enhancements Coming in MongoDB 3.2
Joins and Other Aggregation Enhancements Coming in MongoDB 3.2Joins and Other Aggregation Enhancements Coming in MongoDB 3.2
Joins and Other Aggregation Enhancements Coming in MongoDB 3.2
 
Starting out with MongoDB
Starting out with MongoDBStarting out with MongoDB
Starting out with MongoDB
 
9b. Document-Oriented Databases lab
9b. Document-Oriented Databases lab9b. Document-Oriented Databases lab
9b. Document-Oriented Databases lab
 
Conceptos básicos. Seminario web 4: Indexación avanzada, índices de texto y g...
Conceptos básicos. Seminario web 4: Indexación avanzada, índices de texto y g...Conceptos básicos. Seminario web 4: Indexación avanzada, índices de texto y g...
Conceptos básicos. Seminario web 4: Indexación avanzada, índices de texto y g...
 
1403 app dev series - session 5 - analytics
1403   app dev series - session 5 - analytics1403   app dev series - session 5 - analytics
1403 app dev series - session 5 - analytics
 

Kürzlich hochgeladen

introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 

Kürzlich hochgeladen (20)

10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 

Querying mongo db

  • 1. Query & Aggregation on MongoDB 26 March 2012
  • 2. Agenda  About  Remember: CRUD  Querying  Indexes  Aggregation  QA
  • 3. About  Who Am I? { "Name": "Bogdan Sabau", “Position": "SQL Developer", "Project": "lynda.com", "Why": [ "Big Data", "NoSQL", "Open Source" ] }
  • 4. About  Who Am I? { "Name": "Bogdan Sabau", “Position": "SQL Developer", "Project": "lynda.com", "Why": [ "Big Data", "NoSQL", "Open Source" ] }
  • 5. Remember: CRUD  CREATE new record:  db.zips.insert({"city": "OINKTOWN", "loc": [-89.51557, 32.584132], "pop": 789, "state": "AL"})  READ a record:  db.zips.find({"city": "OINKTOWN"})  UPDATE existing record:  db.zips.update({"city": "OINKTOWN"}, {"city": "OINKTOWN", "loc": [-89.51557, 32.584132], "pop": 1000, "state": "AL"})  db.zips.update({"_id": "999"}, { $set: {"pop":2000}})  db.zips.update({"_id": "999"}, { $set: {"greencity":true}})  DELETE a record:  db.zips.remove({"_id": "999"})
  • 6. Querying  Adhoc queries using find() or findOne() functions  You can query for ranges, set inclusion, inequalities, and more by using $ conditionals.  For more complex queries you can use $where clause  All queries return a cursor  You can make operations on that specific cursor
  • 7. Querying  Simple examples:  db.zips.find({"state": "AL"})  db.zibs.find({"state": "AL"}, {"city":1, "pop":1})  Using "$lt", "$lte", "$gt", "$gte“, "$in", "$or", "$eq", "$not":  db.zips.find({"state": "AL", "pop": {"$lt": 500}}, {"loc":0})  db.zips.find({"state": {"$in": ["AL", "NY"]}, "pop": {"$lt": 50}})  db.zips.find({"$or": [{"pop": {"$lt": 1}}, {"city": "NEW YORK"}]}, {"city":1, "state":1, "pop":1})  NULL match itself but also match a key that doesn’t exists  We can use regular expressions: db.zips.find({"city": /new .*/i})  We can query arrays and embedded documents
  • 8. Querying  $Where queries:  Used when we are dealing with more complex queries  Are using JavaScript  Slower than regular queries because they convert every BSON object to a JavaScript object  Example  db.zips.insert({"_id":"2", "city":"Alba", "county":"Alba", "country":"Romania", "museums": ["Muzeul de Istorie", "Muzeul Unirii"]})  db.zips.find({$where: function() { return this.city == this.county }})  Cursors  Used same as on SQL; we can limit the results, fetch the results and apply JavaScript logic on them
  • 9. Indexes  MongoDB’s indexes work almost identically to typical relational database indexes  Using a query optimizer to find the best index  We can create indexes on embedded documents  Unique indexes are possible  Compound unique indexes  Geospatial indexes
  • 10. Indexes  db.collection.find().explain() – give us information about indexes  db.collection.ensureIndex({“key”:<order>}) – create a new index  db.system.indexes.find() – check all the indexes  db.collection.dropIndex (“indexname”) – drop the index  There is another type of query that is becoming increasingly common (especially with the emergence of mobile devices): finding the nearest N things to a current location. MongoDB provides a special type of index for coordinate plane queries, called a geospatial index.
  • 11. Aggregation  Count: returns the number of documents from the collection  Sum: returns the sum of all the values for a specified field in the grouped document  Distinct: find the distinctive values for a specific key  Group allows you to perform more complex aggregation. You choose a key to group by, and MongoDB divides the collection into separate groups for each value of the chosen key. For each group, you can create a result document by aggregating the documents that are members of that group.
  • 12. Aggregation  Count  db.zips.count()  db.zips.count({"state":"NY"})  Distinct  db.runCommand({"distinct" : "zips", "key" : "state"})  Group: SQL equivlants:  WHERE $match GROUP BY $group  HAVING $match SELECT $project  ORDER BY $sort LIMIT $limit  SUM() $sum COUNT() $sum
  • 13. Aggregation  Group examples  Population by State db.zips.aggregate( { $group : { _id : "$state", totalPop : { $sum : "$pop" } } })  Population by State with condition db.zips.aggregate( { $group : { _id : "$state", totalPop : { $sum : "$pop" } } }, { $match : {totalPop : { $gte : 10*1000*1000 } } }
  • 14. Aggregation  Group examples  Largest and smallest cities by State db.zips.aggregate( { $group: { _id: { state: "$state", city: "$city" }, pop: { $sum: "$pop" } } }, { $sort: { pop: 1 } }, { $group: { _id : "$_id.state", biggestCity: { $last: "$_id.city" }, biggestPop: { $last: "$pop" }, smallestCity: { $first: "$_id.city" }, smallestPop: { $first: "$pop" } } })
  • 15. QA