A very common problem scenario in programming is to get the records or record count by certain fields. For developers familiar with RDBMS, it's like creating a SQL with combination of count function and group by attributes.
For MongoDB too, it's very similar. Let's look at the example below fetching no of employees group by department Ids.
Now, let's understand the above Java method.
What we are doing is that we are first creating a Match criteria, it's like building up where statement in SQL. In the example above, we are putting following two match conditions:
For MongoDB too, it's very similar. Let's look at the example below fetching no of employees group by department Ids.
public Map<Long, Integer> getEmployeeCountMapByDeptId() {
Map<Long, Integer> empCountMap = new HashMap<>();
AggregateIterable<Document> iterable = getMongoCollection().aggregate(Arrays.asList(
new Document("$match",
new Document("active", Boolean.TRUE)
.append("region", "India")),
new Document("$group",
new Document("_id", "$" + "deptId").append("count", new Document("$sum", 1)))));
iterable.forEach(new Block<Document>() {
@Override
public void apply(final Document document) {
empCountMap.put((Long) document.get("_id"), (Integer) document.get("count"));
}
});
return empCountMap;
Now, let's understand the above Java method.
What we are doing is that we are first creating a Match criteria, it's like building up where statement in SQL. In the example above, we are putting following two match conditions:
- employee should be in active state
- employee region is India
Now, for grouping the results, we are putting a group by deptId and returning the count of employees.
Comments
Post a Comment