Search code examples
javaspringmongodbspring-bootspring-data-mongodb

How to calculate the data size of the Mongodb collection using Java MongoOperations?


Mongodb has a mongo shell command db.getCollection('myCollection').dataSize() to return the data size of the given collection. However, this does not work with MongoOperations getCollections() in Spring.

To work around this is what I tried :

myMongoOpObject.executeCommand("db.getCollection(collectionName).dataSize()");

However, this does not work. No errors or console prints. Any help will be appreciated.


Solution

  • You need the collStats command, see here: https://docs.mongodb.com/manual/reference/command/collStats/

    Document stats = operations.executeCommand(new Document("collStats", "collectionName"));
    System.out.println(stats.get("count"));
    System.out.println(stats.get("avgObjSize"))
    System.out.println(stats.get("storageSize"))