javaspringmongodbmongo-shellmongotemplate

MongoDb compact command using spring boot MongoTemplate


Mongo shell command:

db.runCommand({compact: <collection name>})

How can I run same command using MongoTemplate in Spring Boot project?

I tried with:

@Autowired
private MongoTemplate mongoTemplate;
...
mongoTemplate.executeCommand(jsonCommand);
...

but it supports only commands in json.


Solution

  • According to docs you can call executeCommand using DBObject or String as a parameter.

    So one option is simply get the JSON as String:

    String jsonCommand = "{compact: " + collectionName + "}";
    mongoTemplate.executeCommand(jsonCommand);
    

    Or create the DBObject:

    DBObject dbObject = new BasicDBObject("compact", collectionName );
    mongoTemplate.executeCommand(dbObject);
    

    Or even, according to this answer you can create the DBObject from a JSON:

    BasicDBObject dbObject = com.mongodb.BasicDBObject.parse(jsonCommand)
    mongoTemplate.executeCommand(dbObject);