shix
shix

Reputation: 77

How to use Java Spring MongoOperations to execute mongodb collection methods?

I want to calculate the size of the collection for my database. MongoDB has this collection method db.collection.totalsize(). I am having trouble finding how to write the method with the MongoOperations provided by spring.

I am currently trying to use a Basic Query to run the raw query but it is not working. Any help will be appreciated.

Upvotes: 1

Views: 2176

Answers (1)

Fermi-4
Fermi-4

Reputation: 729

MongoOperations is not working here because db.collection.totalSize() is a mongo shell command, not a query

Instead of calling findOne you can call executeCommand()

private final BasicDBObject basicDBObject = new BasicDBObject();
basicDBObject.put("eval", "function() { return db.collection.totalSize(); }");
CommandResult result = mongoOperations.executeCommand(basicDBObject);

Another way to do this is through an instance of MongoDatabase

If you can access an instance of MongoClient you can then get a reference to MongoDatabase

Once you have an instance of MongoDatabase you need to call MongoDatabase.runCommand() and pass in your shell command ('db.collection.totalSize()') as a Bson object and then get your result.

Basically you need to do something like this:

String uri = "mongo uri string"
MongoClient mongoClient = MongoClients.create(uri)
MongoDatabase database = mongoClient.getDatabase("your database");
String commandStr = "db.collection.totalSize()"; // or custom collection name in your case
Bson command = new BsonDocument(commandStr, new BsonInt64(1));
Document commandResult = database.runCommand(command);

In spring, you might be able to @Autowire an instance of one of MongoClient or MongoDatabase in already - check the bean configuration and autoconfiguration in your project.

Upvotes: 1

Related Questions