Friday, April 26, 2019

mongodb aggregation:payment and users sources code (console and in java)


*******Aggregate take agurement of  array // 
let printing every thing  1
db.payment.aggregate();
//// joning collection payment on collection  users on id of payment  id of users  2
db.payment.aggregate([   { $lookup: { from: "users", localField: "id", foreignField: "id" ,as: "user" } }  ])

///unwind to romove from array   and project state fields when to display 3
db.payment.aggregate([   { $lookup: { from: "users", localField: "id", foreignField: "id" ,as: "user" } } ,{"$unwind":"$user"},{$project:{"id":"$id","amount":"$amount","name":"$user.name" }} ])
////group: display unique value base on the key specified  4
db.payment.aggregate([   { $lookup: { from: "users", localField: "id", foreignField: "id" ,as: "user" } } ,{"$unwind":"$user"},{$project:{"id":"$id","amount":"$amount","name":"$user.name" }}, {$group: { _id: {"id" : "$id" }} }])

////display other fieds from the group .. f 5
operators include 
$sum : sum  the specifield constant or field 
$first: display the first value 
$last: display the last value

db.payment.aggregate([   { $lookup: { from: "users", localField: "id", foreignField: "id" ,as: "user" } } ,{"$unwind":"$user"},{$project:{"id":"$id","amount":"$amount","name":"$user.name" }},                           {$group: { _id: {"id" : "$id" },  "sumi":{"$sum": "$amount"}, "name":{"$first": "$name"} ,"id":{"$first": "$id"} }   } ])

project result from the last operation  6

db.payment.aggregate([   { $lookup: { from: "users", localField: "id", foreignField: "id" ,as: "user" } } ,   {"$unwind":"$user"} ,  {$project:{"id":"$id","amount":"$amount","name":"$user.name" }},      {$group: { _id: {"id" : "$id" },"sumi":{"$sum": "$amount"},"name":{"$first": "$name"} ,"id":{"$first": "$id"}   }     }, {$match:{"sumi":{$gt:2500}}}, {$project:{"_id":"0","id":"$id","name":"$name" ,"amount":"$sumi" }}])
//////////////////////////////////////////////////////////////////////////////////////////////////////JAVA CODE  https://youtu.be/ps-jZM05mWE /////////////////////////////////////////////////////////////////////////////////////////////////////////////
MongoCollection<Document> collection = database.getCollection("payment"); 
collection.aggregate(Arrays.asList(
///lookup stage 
Aggregates.lookup("users", "id","id" , "user") 
//group stage ,Aggregates.group("$id",Accumulators.sum("commulativeSum", "$amount"),Accumulators.first("name", "$user.name"))
// match stage ,Aggregates.match(Filters.gt("commulativeSum", 2500)) 
//projection stage ,Aggregates.project(Projections.fields(Projections.include("commulativeSum","name")  ) )
));