1

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

1 Answer 1

2

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
    );
Sign up to request clarification or add additional context in comments.

6 Comments

ReplaceWithOperation/ObjectOperators/UnsetOperation, can not find these classes
Not working. It gives me too many statuses and an incorrect amount of them
ReplaceWithOperation/ObjectOperators/UnsetOperation are imported from - import org.springframework.data.mongodb.core.aggregation.* As per your question you were trying to group using both createdAt & status [combination group] so ofcourse you will be getting too many statuses. What is it you were trying to achieve ?
I try to get documents by every year in the spring framework using Aggregation class
check the updated answer. Have added Project stage before Group
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.