【问题标题】:How to use Java Spring MongoOperations to execute mongodb collection methods?如何使用 Java Spring MongoOperations 执行 mongodb 集合方法?
【发布时间】:2021-09-07 17:24:31
【问题描述】:

我想为我的数据库计算集合的大小。 MongoDB有这个收集方法db.collection.totalsize()。我很难找到如何使用 spring 提供的 MongoOperations 编写方法。

我目前正在尝试使用Basic Query 来运行原始查询,但它不起作用。任何帮助将不胜感激。

【问题讨论】:

  • 你能贴出任何代码吗?
  • 这是我尝试过的MongoOperations mongoOperations; this.mongoOperations.findOne(new BasicQuery("db."+collectionName+".totalSize()"), Long.class)
  • 您能展示一下您是如何使用MongoTemplate 类的吗?你有MongoRepository 设置吗?
  • 没有。这些操作是在 MongoOperations 上完成的。代码库有一个存储库接口的实现。抱歉,我需要重新提出问题。
  • 错误是什么?

标签: java spring mongodb spring-boot


【解决方案1】:

MongoOperations 在这里不起作用,因为 db.collection.totalSize()mongo shell command,而不是查询

您可以拨打executeCommand(),而不是拨打findOne

private final BasicDBObject basicDBObject = new BasicDBObject();
basicDBObject.put("eval", "function() { return db.collection.totalSize(); }");
CommandResult result = mongoOperations.executeCommand(basicDBObject);

另一种方法是通过MongoDatabase的实例

如果您可以访问MongoClient 的实例,那么您可以获得对MongoDatabase 的引用

一旦您拥有MongoDatabase 的实例,您需要调用MongoDatabase.runCommand() 并将您的shell 命令('db.collection.totalSize()') 作为Bson 对象传递,然后获取您的结果。

基本上你需要做这样的事情:

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);

在春季,您可能已经可以 @Autowire 一个 MongoClientMongoDatabase 之一的实例 - 检查项目中的 bean 配置和自动配置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-29
    相关资源
    最近更新 更多