NXM 201 and NXM 301 Aggregation Queries
Table of contents
NXM 201
1. Mongodb - advance queries [https://students.masaischool.com/assignments/25108/problems/27000/121343]
6 Questions
Checkout the sample database Here [https://pastebin.com/raw/W1NgY8XQ]
Import this json into your mongodb collection.
Write following queries:
1. Find all the countries in region "Asia"
db['mongodb-advance-queries'].find({
"region":"Asia"
});
----------------------------------------------------------------
2. Find all the countries with currency: "EUR"
db['mongodb-advance-queries'].find({
"currency":"EUR"
})
-----------------------------------------------------------------------
3. Find all the countries whose timezone's gmtOffset is 3600
-> Documentation reference - https://www.mongodb.com/docs/manual/tutorial/query-array-of-documents/
db['mongodb-advance-queries'].find({
"timezones.gmtOffset" : {$eq:3600}
})
-------------------------------------------------------------------
4. Find all the countries whose timezone's gmtOffset is 3600 AND
timezone name is Central European Time (or CET)
// 4. Find all the countries whose timezone's gmtOffset is 3600 AND
// timezone name is Central European Time (or CET)
db['mongodb-advance-queries'].find({
timezones: {
$elemMatch:{
tzName:"Central European Time",
gmtOffset:3600
}
}
})
Why we should use $eleMatch ?
To Ensure Both Conditions Are True for the Same Element:
You need to use the $elemMatch operator. This operator ensures
that both conditions are true within the same element of the array.
Explanation of $elemMatch:
$elemMatch ensures that both tzName and gmtOffset are matched
within the same element of the timezones array.
WHAT NOT TO DO HERE
You cannot query here using the below query
db['mongodb-advance-queries'].find({
"timezones.tzName": { $eq: "Central European Time" },
"timezones.gmtOffset": { $eq: 3600 }
})
because
No, your query does check both conditions together,
but it applies them independently across all elements of
the timezones array. MongoDB's
query engine treats arrays in a way that requires some clarification:
This query matches documents where:
At least one element in the timezones array has tzName
equal to "Central European Time".
At least one element in the timezones array has gmtOffset equal to 3600.
These two conditions do not necessarily need to be true in
the same array element. For example, the query could return
a document where:
One array element has tzName: "Central European Time" but a different
gmtOffset.
Another array element has gmtOffset: 3600 but a different tzName.
-------------------------------------------------------------------------
5. Find All the countries with more than 1 time zone (hint: size of array)
// 5. Find All the countries with more than 1 time zone (hint: size of array)
db['mongodb-advance-queries'].find({
$expr: {
$gt: [{ $size: "$timezones" }, 1]
}
})
--------------
Explaination of the above query (5th query)
`db['mongodb-advance-queries']`
This part specifies the database collection you are querying.
In this case, it is called mongodb-advance-queries.
The db object represents the database connection, and the
collection is accessed using the bracket notation.
.find({...}):
The find method is used to retrieve documents from the
specified collection that match the criteria defined
in the query object.
$expr:
This operator allows you to use aggregation expressions
within the query. It enables you to perform operations
on the fields of the documents and evaluate them dynamically.
Without $expr, you would not be able to use aggregation
operators like $size directly in the query.
$gt:
This is a comparison operator that stands for "greater than."
It takes two arguments and returns true if the first argument
is greater than the second.In this case, it is used to compare
the size of the timezones array to the number 1.
$size:
This operator returns the number of elements in an array. In this query, it is applied to the timezones field of each document.
The expression {$size: "$timezones"} evaluates to the count
of elements in the timezones array for each document.
[{ $size: "$timezones" }, 1]:
This array contains two elements: the first is the size of
the timezones array for the current document, and the second is the
number 1.The $gt operator will check if the size of the
timezones array is greater than 1.
Summary of the Query's Purpose
The overall purpose of this query is to find and retrieve all
documents (countries) in the mongodb-advance-queries collection
that have more than one time zone. It does this by checking if
the length of the timezones array for each document is greater
than 1. If it is, that document will be included in the results
returned by the query.
Example Scenario
For example, if you have a country document like this:
json
{
"name": "Russia",
"timezones": [
{"zoneName": "Europe/Moscow"},
{"zoneName": "Asia/Vladivostok"},
{"zoneName": "Asia/Yekaterinburg"}
]
}
This document would match the query because the timezones
array has three elements (zones), which is greater than one.
In contrast, a country document with a single time zone would not match, as its array size would not exceed one.
---------------------------------------
-----------------------------------------------------------------
6. Find All the countries with "Korean" translation (KR)
// 6.Find All the countries with "Korean" translation (KR)
db['mongodb-advance-queries']
.find({
"translations.kr": {$exists: true}
})
---------------------------------------------------------
one sample data
{
"id": 1,
"name": "Afghanistan",
"iso3": "AFG",
"iso2": "AF",
"numeric_code": "004",
"phone_code": "93",
"capital": "Kabul",
"currency": "AFN",
"currency_name": "Afghan afghani",
"currency_symbol": "؋",
"tld": ".af",
"native": "افغانستان",
"region": "Asia",
"subregion": "Southern Asia",
"timezones": [
{
"zoneName": "Asia\/Kabul",
"gmtOffset": 16200,
"gmtOffsetName": "UTC+04:30",
"abbreviation": "AFT",
"tzName": "Afghanistan Time"
}
],
"translations": {
"kr": "아프가니스탄",
"pt-BR": "Afeganistão",
"pt": "Afeganistão",
"nl": "Afghanistan",
"hr": "Afganistan",
"fa": "افغانستان",
"de": "Afghanistan",
"es": "Afganistán",
"fr": "Afghanistan",
"ja": "アフガニスタン",
"it": "Afghanistan",
"cn": "阿富汗",
"tr": "Afganistan"
},
"latitude": "33.00000000",
"longitude": "65.00000000",
"emoji": "🇦🇫",
"emojiU": "U+1F1E6 U+1F1EB"
}
Here are more datasets:
https://data.world/datasets/json
https://github.com/neelabalan/mongodb-sample-dataset
Bonus:
refer official docs for following operators.
Update the data using:
$set
$rename
$push $pop
$min $max
$unset
Feel free to update any data since this is bonus part
2. Mongo Aggregation-1
1. Mongo Aggregation-1 [5 question] [https://students.masaischool.com/assignments/25109/problems/27030/121344]
Go to https://media.mongodb.org/zips.json and download the large dataset of zips
https://www.mongodb.com/docs/manual/tutorial/aggregation-zip-code-data-set/
sample data
{
"_id": "01001",
"city": "AGAWAM",
"loc": [
-72.622739,
42.070206
],
"pop": 15338,
"state": "MA"
}
Write aggregation queries for following:
find largest population city in every state
find average population per state by cities
find the lowest population city
Self Practice:
Learn about $project aggragation stage yourself
Learn about $count stage yourself
2. mongodb_aggregation-II 10 Question [https://students.masaischool.com/assignments/25109/problems/30013/121345]
3. Aggregations - II
1. Aggregation-Multiple-lookup-stages 6 Question
[https://students.masaischool.com/assignments/25110/problems/29014/121346]
2. Aggregation sale transactions 2 Question [https://students.masaischool.com/assignments/25110/problems/29015/121347]
3. Aggregation Graph Lookup 1 Question
[https://students.masaischool.com/assignments/25110/problems/30037/121348]
4. Aggregation aggregation_population 6 Question
[https://students.masaischool.com/assignments/25110/problems/30034/121349]
4 MongoDB Indexing
1. MongoDB Indexing 8 Questions
[https://students.masaischool.com/assignments/25313/problems/29070/121532]
2. Aggregation_date_range 7 Questions
[https://students.masaischool.com/assignments/25313/problems/30245/121533]
5. Timers and Internals
1.aggregation_advanceQueries-II - 5 Questions
[https://students.masaischool.com/assignments/25817/problems/30639/122146]
6. CI/CD assignment - 4 Question
[https://students.masaischool.com/assignments/26136?tab=assignmentDetails]
NXM 301
7.SQL Assignment Day 2 [https://students.masaischool.com/assignments/25056?tab=assignmentDetails]
1. BANK Problem -> 20 Problems
2. SQL Student Table -> 8 Problems
3. SQL Bakery -> 1 Question
4. SQL employee Table -> 4 question
5. SQL 2 - CP Platform -> 20 question [https://students.masaischool.com/assignments/25117?tab=assignmentDetails]
[https://cp.masaischool.com/assignments/1280/view]
8. SQL DAY 3 [https://students.masaischool.com/assignments/25122?tab=assignmentDetails]
1. 25 problems [https://cp.masaischool.com/assignments/1281/view]
2. 25 problems [https://cp.masaischool.com/assignments/1282/view]
3. 10 Problems [https://cp.masaischool.com/assignments/1283/view]
9. SQL DAY -4
1. 1 Question [https://students.masaischool.com/assignments/25057?tab=assignmentDetails]
Subscribe to my newsletter
Read articles from Surya Prakash Singh directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Surya Prakash Singh
Surya Prakash Singh
A full stack developer from India. Html | Css | Javascript | React | Redux | Tailwind | Node | Express | Mongodb | Sql | Nosql | Socket.io