Erdem Aydemir
Erdem Aydemir

Reputation: 389

Spring Boot Data Aggregation with MongoDB

db.yorum.aggregate([
    { $match: { bayiId: "5848631a2aa9191f78ff3847" }},
    { $group: { _id: "$bayiId" ,avg: { $avg: "$yildiz" }}}
])

How can i will use in Spring Boot?

i need a "yildiz" avg.

my collection

avg_yildiz

MongoDBConfig.java

@Configuration
@ComponentScan(basePackages="com.application.repository")
@EnableMongoRepositories(basePackages = "com.application.repository")
@EnableMongoAuditing(modifyOnCreate=false)
public class MongoDBConfig extends AbstractMongoConfiguration {

    @Override
    protected String getDatabaseName() {
        return "application";
    }

    @Override
    public Mongo mongo() throws Exception {
        return new MongoClient("localhost", 27017);
    }

    @Bean
    public MongoExceptionTranslator exceptionTranslator() {
        return new MongoExceptionTranslator();
    }

    @Bean
    public LoggingEventListener logginEventListener(){
        return new LoggingEventListener();
    }

}

MongoDB Configure class. How can i add mongoTemplate ?

Edit

java.lang.IllegalArgumentException: Unsupported entity com.application.domain.Bayi! Could not determine IsNewStrategy.

How can i save repository?

bayiRepository.save(seciliBayi);

Upvotes: 1

Views: 9039

Answers (1)

notionquest
notionquest

Reputation: 39226

Here is the Spring equivalent. Please note that you can't achieve the aggregation using methods in Repository class like normal query operations.

Code:-

import static org.springframework.data.mongodb.core.aggregation.Aggregation.group;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.match;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.newAggregation;
public String findAverageForYourm(String bayiId) {

    TypedAggregation<Yorum> aggregation = newAggregation(Yorum.class,
             match(Criteria.where("bayiId").is(bayiId)),
             group("bayiId").avg("yildiz").as("avgVal")
        );


    MongoOperations mongoOperations = getMongoConnection();

    AggregationResults<Yorum> results = mongoOperations.aggregate(aggregation, Yorum.class);

    System.out.println(results.getRawResults().get("result"));

    return results.getRawResults().get("result").toString();

}

MongoTemplate Object:-

You can replace the getMongoConnection() with mongoTemplate if you have the object. This is my project specific configuration. I have just added it for clarification.

@SuppressWarnings("resource")
public MongoOperations getMongoConnection() {

    return (MongoOperations) new AnnotationConfigApplicationContext(SpringMongoConfig.class)
            .getBean("mongoTemplate");
}

Plain syntax:-

AggregationResults<OutputType> results = mongoTemplate.aggregate(agg, "INPUT_COLLECTION_NAME", OutputType.class);

Output:-

[ { "_id" : "5848631a2aa9191f78ff3847" , "avgVal" : 4.333333333333333}]

Config class:-

@Configuration
@EnableMongoRepositories(basePackageClasses = RepositoryPackage.class)
@ComponentScan(basePackageClasses = RepositoryPackage.class)
public class SpringMongoConfig extends AbstractMongoConfiguration {

    public @Bean MongoDbFactory mongoDbFactory() throws Exception {

        return new SimpleMongoDbFactory(new MongoClient(), "localhost");
    }

    public @Bean MongoTemplate mongoTemplate() throws Exception {

        MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory());

        return mongoTemplate;

    }

    @Override
    protected String getDatabaseName() {
        return "localhost";
    }

    @Override
    public Mongo mongo() throws Exception {
        MongoClient client = new MongoClient("localhost");
        client.setWriteConcern(WriteConcern.SAFE);
        return client;
    }

}

Upvotes: 1

Related Questions