1

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.

7
  • Can you post any code? Commented Sep 7, 2021 at 18:01
  • This is what I have tried MongoOperations mongoOperations; this.mongoOperations.findOne(new BasicQuery("db."+collectionName+".totalSize()"), Long.class) Commented Sep 7, 2021 at 18:06
  • Can you show how you use the MongoTemplate class? Do you have a MongoRepository set up? Commented Sep 7, 2021 at 18:16
  • No. The operations are done on MongoOperations The codebase has an implementation of a repository interface. Sorry, I need to reframe the question. Commented Sep 7, 2021 at 18:23
  • What is the error? Commented Sep 7, 2021 at 18:28

1 Answer 1

1

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.

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

Comments

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.