MongoDB Aggregation
MongoDB Aggregation
Group :
The names field uses the $push operator to add the same field from each
document in the group to an array
The $$ROOT value is a reference to the current document being
processed in the pipeline , which represents the complete document.
The value of $sum is 1 , which means that for each document in the group
, the value of “number” will be incremented by 1
See in 35 age group count to ensure
Query for it :
db.teachers.aggregate([ {$match : {gender :
“male”}} , {$group : {_id:”$age” , count : {$sum :
1}}} , {$sort : {count : -1}} ])
$toDouble operator :
Unwind operator :
It breaks array and create different
document with different values of hobbies
from data.
Answer :
Now no nested array are here
Answer :
db.students.aggregate([ {$unwind :
“$hobbies”} , { $group : {_id:”$hobbies” ,
count : { $sum : “$1”} }} ])
Answer :
db.students.aggregate([{ $group : { _id :
null , avg : { $avg : “$age”}} }])
Another way :
Worked but if any one document doesn’t have field hobbies than error will
occur to avoid that error :
ERROR : PlanExecutor error during aggregation
db.students.aggregate([ { $group : { _id:null , count : { $sum : { $size :
{ $ifNull : ["$hobbies",[]]} } } } } ])
Syntax :
{ $size : <expression> }
{ $ifNull : <expression> ,
<replacementExpression> }
$filter :
Syntax : $filter : {
input:<array expression>,
as : <identifier>,
cond : <expression>
}
Cond : Specifies the condition that must be met in order for an element
to be included in the result set. The expression must return either true or
false.
Que : Find Average of score for students whose age is greater than 20
Answer :