♠ MongoDB Aggregation Framework and Map Reduce ♠

✨ What is Database ?

✨ What is NoSQL ?

✨ What is MongoDB ?

✨ What is MongoDB Aggregation Framework ?

✨ What is Aggregation Pipeline ?

✨ What is Map Reduce Function ?

Let’s begin with Task :🤩

✨ Task Description📄

mongoimport sample.json  -d  <database_name> -c <collection_name>    --jsonArray

👉🏻 Lets connect to mongodb shell :

# to see databases
show dbs
# to see collections
use <database_name>
show collections

👉🏻 First let’s understand what our data contains and what our goal is ?

👉🏻 We will perform this using two MongoDB Aggregation Framework :

✨ Now let’s begin with task ….

👉🏻 Method 1: Aggregation Pipeline

db.countries.aggregate([{$group: {_id: {Language: “$Language”}, totalCountry: {$sum: 1}}}, {$sort: {totalCountry: 1}}])
# {$group: {_id: {Language: "$Language"} --> group by Language# totalCountry: {$sum: 1} --> count the total countries asscoiated with that language# {$sort: {totalCountry: 1} --> sort them in ascending order

👉🏻 Method 2: Map Reduce Function

# Map reduce functions# Syntax :var mapFunction = function() { … };var reduceFunction = function(key, values) { … };db.runCommand(
{
mapReduce: <input-collection>,
map: mapFunction,
reduce: reduceFunction,
out: { merge: <output-collection> },
query: <query>
}
)

👉🏻 Declaring Map variable :

var mapFunc1 = function()  { 
var cntry = emit(this.Language, this.CountryName);
$split: [ cntry, "," ];
};
# defined country variable which will be grouping the data based on Language and Country Name and then splitting the data by comma

👉🏻 Declaring Reduce variable :

var ReduceFunc1 = function(keyLang, valuesCountryName) {  
return valuesCountryName.length;
};
# after grouping, here we are counting the number of countries after the output is been sent by mapper

👉🏻 Using Map Reduce Function :

db.countries.mapReduce( 
mapFunc1,
ReduceFunc1,
{out: "map_reduced"}
)
# now using map reduce function and saving it in map_reduced collection

👉🏻 Now let’s do query :

db.map_reduced.find().sort( { } )

So finally, data is sorted as we wanted !!! 🎉🎉

Thanks for Reading !! 🙌🏻😁📃

🔰 Keep Learning !! Keep Sharing !! 🔰

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store