简体   繁体   中英

spring data Mongo db aggregation

I use the following aggregation to count "alertsources" on document "alert" that has a specifique "alertsources.date_creation" but I don't know why it counts all the alertsources instead of those who has the criteria :

final Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("alertsources.date_creation").regex(date)),
                Aggregation.match(Criteria.where("descA").is(alertName)),

                //regex(".*"+date+".*")
                Aggregation.unwind("alertsources"),
                Aggregation.unwind("descA"),
                Aggregation.group().count().as("count"));

        //System.out.println("----------"+mongoTemplate.aggregate(aggregation, Alert.class, MentionCount.class).getRawResults()+"-----");
        List<MentionCount> agregResult = mongoTemplate.aggregate(aggregation, Alert.class, MentionCount.class).getMappedResults();

I solved the problem, I should have applied $match before and after $unwind :

Aggregation.match(Criteria.where("alertsources.date_creation").regex(".*"+date+".*")),
                Aggregation.match(Criteria.where("descA").is(alertName)),

                //regex(".*"+date+".*")
                Aggregation.unwind("alertsources"),
                Aggregation.unwind("descA"),
                Aggregation.match(Criteria.where("alertsources.date_creation").regex(".*"+date+".*")),
                Aggregation.group().count().as("count")

All the credit goes to @ Neil Lunn , after doing research I found his original answer on the matter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM