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.
MongoOperations mongoOperations; this.mongoOperations.findOne(new BasicQuery("db."+collectionName+".totalSize()"), Long.class)MongoTemplateclass? Do you have aMongoRepositoryset up?