How to use Multiple Aggregation Operations in MongoDB Aggregation

Posted By : Bobby Sharma | 31-May-2018

Aggregation operation represent a single Operaton in Aggreation pipepline.In MongoDB Documents enter a multi-stage pipeline that transforms the documents into aggregated results.In Application Layer We can use Aggregation Operation list to Obtain aggregated result. To underStand Lets Take Example and create Collection name Asset and Create Some Entries in Asset. Here We are Creating Some Entries in Asset Collection With Country id 4,and taking list of Organization types And organizations Services:

{"_id":10,"name" : "Asset1","organizationTypes":[{"value":344,"label":"Kummunal"}],"organizationServices":[{"value":171,"label" : "Personlig pleje"}]}
{"_id":11,  "name" :"ERP", "countryId" : 4,"organizationTypes" :[ {"value":346, "label":"public" } ],"organizationServices":[{"value":169,"label" : "IT"}]}
{"_id":12, "name" : "Adobe","countryId":4,"organizationTypes" : [ {"value":345,"label" : "private"}],"organizationServices" : [ { "value" : 168,"label" : "Hspitality"}]}

Now We Are Going to Fetch All Distinct Value of Organization type And organization Services From Asset Document which contain List of Organization Types And Organization Services. Same Result Can we Fetch by Using MongoDB Distinct Query But Suppose If We Have Multiple Fields With list Then We have to Interact with data Base multiple Time So We Going to Do This In Single Query Using $match,$unwind And $group Operation in Aggregation Pipeline :

1.$match (MatchOperation) :$match operation Filter the documents to pass only those documents that match the specified condition to the next stage of Aggregation pipeline.

2.$unwind (UnwindOperation):$unwind allow you to peel off a document for each element in Array and returns that resulting document. it would be the equivalent of "for each item in the array, return a document with only that item.

3:$group (GroupOperation):$group Operation group documents by some specified expression or key and outputs to the next stage will be a document for each distinct grouping.

 

db.getCollection('asset').aggregate([
    {$match:{'countryId':NumberLong(4)}},
    {$unwind:'$organizationTypes'},
    {$unwind:'$organizationServices'},
    {$group: { _id: "1",
    organizationTypes:{$addToSet:'$organizationTypes'},
    organizationServices:{$addToSet:'$organizationServices'}}},
  ])

The result of the Above Aggregation Return us Distinct Values of Organization types and Organization Service, Below is the Result:

{
    "_id" : "1",
    "organizationTypes":[{"value":346,"label":"public"}, {"value" : 345, "label" : "private"}, {"value:344, "label" : "Kummunal"}],
    "organizationServices":[{"value":169,"label":"IT"}, { "value":168,"label":"Hspitality},{"value":171,"label":"Personlig pleje"}]
}

Above result Can Also be Get Through Aggregation Operations which Can be Done be in Service Layer Also, There are Two Ways of Using Aggregation Operation:

1.Using Aggregation operation one by one .

MatchOperation,UnwindOperation ,GroupOperation are Interfaces which extends AggregationOperation interface .To create Aggregation we Use Aggregation static Constructor which take AggregationOperation List.

MatchOperation matchOperation=match(Criteria.where("countryId").is(4));
UnwindOperation unwindOperation= unwind("organizationTypes");
UnwindOperation unwindOperation2= unwind("organizationServices");
GroupOperation groupOperation1 =group().addToSet("organizationTypes").as("organizationTypes").addToSet("organizationServices").as("organizationServices");      
Aggregation aggregation=Aggregation.newAggregation(matchOperation,unwindOperation,unwindOperation2,groupOperation);
mongoTemplate.aggregate(aggregation, Asset.class, AggregationQueryResultDto.class);

2.Using Aggregation operation List.

 List operations=new ArrayList<>();
 operations.add(match(Criteria.where("countryId").is(4)));
 operations.add(unwind("organizationTypes"))
 operations.add(unwind("organizationServices"));
 GroupOperation groupOperation=group().addToSet("organizationTypes").as("organizationTypes").addToSet("organizationServices").as("organizationServices");
 operations.add(groupOperation);
 Aggregation aggregation = Aggregation.newAggregation(operations);
 mongoTemplate.aggregate(aggregation, Asset.class, AggregationQueryResultDto.class);

AggregationOperation Interface has toDocument() method ,toDocument() method turn Aggregation Operation into a Document by using the AggregationOperationContext.

Request for Proposal

Name is required

Comment is required

Sending message..