Home > Enterprise >  How to convert MongoDB $group and count/$sum aggregation to a Java Object using Aggregation?
How to convert MongoDB $group and count/$sum aggregation to a Java Object using Aggregation?

Time:12-12

I have a MongoDB query, which allows you to sum status field and get Documents yearly:

db.collection.aggregate([
    {
        $group: {
            _id: {
                year: { 
                        $year: "$createdAt" 
                },
                status: "$status"
            },
            count: { 
                     $sum: 1
            }
        }
    },
    { $replaceWith: { $mergeObjects: [ "$_id", "$$ROOT" ] } },
    { $unset: "_id" }
])

I want to translate it into Java Aggregation and send query with MongoOperations. I'm doing it like that:

GroupOperation groupOperation = Aggregation.group(Fields.fields("$createdAt")).sum(String.valueOf(1)).as("yearly");
Aggregation aggregation = Aggregation.newAggregation(groupOperation);
AggregationResults<String> strings = mongoOperations.aggregate(aggregation, "collection", String.class);

But it's not working. Can someone help me with a solution to this problem?

I try many ways, with count, sum, but it does not work

CodePudding user response:

Try this

AggregationResults<Object> results = mongoOperations.aggregate(
            Aggregation.newAggregation(
                    Aggregation.project("status").and(DateOperators.Year.yearOf("createdAt")).as("year"),
                    Aggregation.group(
                            Fields.from(
                                    Fields.field("year", "year"),
                                    Fields.field("status", "status")
                            )
                    ).count().as("count"),
                    ReplaceWithOperation.replaceWithValueOf(
                            ObjectOperators.MergeObjects.mergeValuesOf("$_id").mergeWith("$$ROOT")
                    ),
                    UnsetOperation.unset("_id")
            ),
            "collection",
            Object.class
    );
  • Related