简体   繁体   中英

Equivalent mongodb find({}) in spring data

In mongo, it's possible to find all documents without a condition with this way:

db.collectionName.find({});

How I can do it using spring data?

I need to do this only to count the quantity of documents in the collection. I don't have the class, only the name of collection. I tried mongoTemplate.count and mongoTemplate.findAll , but both requires or the model class or some Query.

The below code should return the count of all documents in Mongo collection unconditionally. There is no conditions given for query object. It doesn't require the model as well.

Input the collection name accordingly in the below code.

Documents Count:-

MongoOperations mongoOperations = getMongoConnection();
Query query = new Query();
return mongoOperations.count(query, collectionName);

My MongoOperations Bean:-

You might have similar code in your project. SpringMongoConfig is my custom class to get the connection.

public MongoOperations getMongoConnection() {

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

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