MongoDB的`compact`命令使用Spring Boot的MongoTemplate。

huangapple go评论74阅读模式
英文:

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

根据文档,你可以使用DBObjectString作为参数来调用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);

huangapple
  • 本文由 发表于 2023年2月18日 01:15:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/75487361.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定