Agregat MongoDB
// MonogDB Aggregation Framework
// $project -> $match -> $group -> $sort -> ouput
// $count, $skip, Sunwind,
// $match
db.users.aggregate([
{ stage 1}, $project
{ stage 2}, $match
{ stage 3}, $group
{ stage 4}, $sort
]);
* match :
db.users.aggregate([{$match:{'status':'inactive'}}]).pretty();
* group :
// group by department
db.users.aggregate([{$group:{_id:'$department'}}]).pretty();
{"id" : "IT" } {
{"_id" : "TECH" }
{_"id" : "HR" }
- multiple group
db.users.aggregate([{$group:{_id:{age:'Şage',gender:'$gender'}}}]).pretty();
{"id" : { "age" : "27", 'gender' : "female" }}
{"_id" : { "age" : "25", "gender" : "female" } }
{ "_id" : { "age" : "26" "gender" : "male" } }
{ "_id" : { "age" : "24", "gender" : "male" } }
{ "_id" : { "age" : "22", "gender" : "male" } }
{"_id" : { "age" : "27", "gender" : "male" } }
* sort
db.users.aggregate([{$group:{_id:'$department'}},{$sort:{_id:1}}]);
* match
db.users.aggregate([{$match:{status:'active'}},{$project:{name:1,email:1}}]).pretty();
* count
db.users.aggregate([{$match:{status:'inactive'}},{$count:'totals'}]);
* limit
db.users.aggregate([{$match:{status:'active'}},{$project:{name:1,email:1}},{Slimit:2}]).pretty();
* unwind
- It is used for array attribute to show seprate result for that array.
db.users.aggregate([{$unwind:"$language"},{$match:{status:'inactive'}},{$project:{name:1,language:1}}]).pretty();
db.users.aggregate([{$unwind:'$language'},{$group:{_td:'$language'}}]);
* lookup
- Joining two tables
db.users.aggregate({
$lookup:{
from: "department",
localField:"dept", 06
foreignField: "name"
as: "anything"
})
* out
- It will create the new collection with that name and storing the data result into it.
db.users.aggregate([{ $match:{status:'active'}},{$project:{email:1,name:1, id:0}},{'$out':'info'}]).pretty();
Abhishek