1
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);

1 Answer 1

1

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;
    }

}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for help. But i edit my post. i have a MongoDBConfig.java.How can i add mongotemplate in class?
Added my config class. You can refer the mongoTemplate on this.
İ have a problem. when i changed my mongoconfigure, i can't save data. i added my post look pls.

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.