运行命令
Overview
在本指南中,您可以学习;了解如何使用 MongoDatabase.runCommand()
方法运行原始数据库操作。原始数据库操作是可以直接在MongoDB Server CLI上执行的命令。这些命令包括管理和诊断任务,例如获取服务器统计信息或初始化副本集。在 MongoDatabase
的实例上使用 Bson
命令对象调用 runCommand()
方法,以运行原始数据库操作。
重要
首选驱动程序方法而非数据库命令
驱动程序为许多数据库命令提供了封装方法。我们建议尽可能使用驱动程序方法,而不是执行数据库命令。
要执行管理任务,请使用 MongoDB Shell而不是 Java 驱动程序。 在shell内调用 db.runCommand()
方法是发出数据库命令的首选方法,因为它在shell和驱动程序之间提供了一致的接口。
runCommand()
方法接受 Bson
对象形式的命令。默认情况下,runCommand
返回类型为 org.bson.Document
的对象,其中包含数据库命令的输出结果。作为可选的第二个参数,您可以指定 runCommand()
的返回类型。
运行命令示例:完整文件
在以下样本代码中,我们发送 dbStats
命令以请求特定 MongoDB 数据库的统计信息。
注意
此示例使用连接 URI 连接到MongoDB实例。 要学习;了解有关连接到MongoDB实例的更多信息,请参阅连接指南。
// Runs a database command by using the Java driver package org.example; import org.bson.BsonDocument; import org.bson.BsonInt64; import org.bson.Document; import com.mongodb.MongoException; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoDatabase; import org.bson.conversions.Bson; public class RunCommand { public static void main(String[] args) { // Replace the uri string with your MongoDB deployment's connection string String uri = "<connection string uri>"; try (MongoClient mongoClient = MongoClients.create(uri)) { MongoDatabase database = mongoClient.getDatabase("sample_mflix"); try { Bson command = new BsonDocument("dbStats", new BsonInt64(1)); // Retrieves statistics about the specified database Document commandResult = database.runCommand(command); // Prints the database statistics System.out.println("dbStats: " + commandResult.toJson()); } catch (MongoException me) { // Prints a message if any exceptions occur during the command execution System.err.println("An error occurred: " + me); } } } }
运行上述命令后,您将看到与下面类似的输出结果:
dbStats: {"db": "sample_mflix", "collections": 5, "views": 0, "objects": 75595, "avgObjSize": 692.1003770090614, "dataSize": 52319328, "storageSize": 29831168, "numExtents": 0, "indexes": 9, "indexSize": 14430208, "fileSize": 0, "nsSizeMB": 0, "ok": 1}
更多信息
API 文档
有关运行数据库命令的方法的更多信息,请参阅以下API文档: