英文:
MongoDb compact command using spring boot MongoTemplate
问题
在Spring Boot项目中如何使用MongoTemplate运行相同的命令?
我尝试了以下方法:
@Autowired
private MongoTemplate mongoTemplate;
...
mongoTemplate.executeCommand(jsonCommand);
...
但它只支持 JSON 格式的命令。
英文:
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.
答案1
得分: 0
根据文档,你可以使用DBObject
或String
作为参数来调用executeCommand
方法。
因此,一种选项是将JSON作为字符串获取:
String jsonCommand = "{compact: " + collectionName + "}";
mongoTemplate.executeCommand(jsonCommand);
或者创建DBObject
:
DBObject dbObject = new BasicDBObject("compact", collectionName);
mongoTemplate.executeCommand(dbObject);
甚至,根据这个答案,你可以从JSON创建DBObject
:
BasicDBObject dbObject = com.mongodb.BasicDBObject.parse(jsonCommand);
mongoTemplate.executeCommand(dbObject);
英文:
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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论