Overview
在本指南中,您可以学习;了解如何使用.NET/ C#驱动程序来运行数据库命令。 您可以使用数据库命令执行各种管理和诊断任务,例如获取服务器统计信息、初始化副本集或运行聚合管道。
重要
首选驱动程序方法而非数据库命令
驱动程序为许多数据库命令提供了包装器方法。如果可能,我们建议使用这些方法,而不是执行数据库命令。
要执行管理任务,请使用MongoDB Shell而不是.NET/C#驱动程序。Shell提供了驱动程序中可能不可用的辅助工具。
如果驱动程序或shell中没有可用的辅助工具,则可以使用 db.runCommand() shell方法或驱动程序的 RunCommand() 和 RunCommandAsync() 方法,如本指南中所述。
样本数据
本指南中的示例使用Atlas示例数据集中的 sample_restaurants.restaurants集合。要学习;了解如何创建免费的MongoDB Atlas 群集并加载示例数据集,请参阅.NET/ C#驱动程序入门 。
执行命令
要运行数据库命令,请创建指定该命令的 BsonDocument对象,并将其作为参数传递给 RunCommand() 或 RunCommandAsync() 方法。 您可以通过指定类型参数来指定这些方法返回的类型。 您可以使用 BsonDocument 类型返回命令响应,也可以指定自己的强类型类来反序列化命令响应。
以下示例对数据库运行 hello 命令,该命令会返回有关服务器的信息。 选择 Synchronous 或 Asynchronous标签页以查看相应的代码。
var command = new BsonDocument("hello", 1); var result = database.RunCommand<BsonDocument>(command);
var command = new BsonDocument("hello", 1); var result = await database.RunCommandAsync<BsonDocument>(command);
提示
To view a full list of database commands and their corresponding parameters, see Database Commands in the MongoDB Server manual.
设置读取偏好
RunCommand() 方法不会继承您可能在 MongoDatabase实例上设立的读取偏好(read preference)。 默认下,RunCommand() 使用 primary读取偏好(read preference)。
您可以将 ReadPreference实例作为参数传递给 RunCommand(),为命令执行设置设立读取偏好(read preference),如以下示例所示。 选择 Synchronous 或 Asynchronous标签页以查看相应的代码。
var command = new BsonDocument("hello", 1); var result = database.RunCommand<BsonDocument>(command, ReadPreference.Secondary);
var command = new BsonDocument("hello", 1); var result = await database.RunCommandAsync<BsonDocument>(command, ReadPreference.Secondary);
提示
要学习;了解有关读取偏好(read preference)选项的更多信息,请参阅MongoDB Server手册中的读取偏好。
响应
RunCommand() 方法返回的原始命令响应文档包含以下字段:
字段 | 说明 |
|---|---|
| 特定于数据库命令的字段。 示例, |
| 指示命令是成功 ( |
| 包含签名集群时间的文档。 集群时间是用于对操作进行排序的逻辑时间。 此字段仅适用于在副本集或分片的集群上运行的命令。 |
| 操作执行的逻辑时间。 此字段仅适用于在副本集或分片的集群上运行的命令。 |
提示
要学习;了解有关逻辑时间的更多信息,请参阅有关逻辑时钟的维基百科条目。
例子
以下示例运行 dbStats 命令来检索sample_restaurants数据库的存储统计信息,然后对返回的 BsonDocument对象使用 ToJson() 方法来打印命令结果。 选择 Synchronous 或 Asynchronous标签页以查看相应的代码。
var command = new BsonDocument("dbStats", 1); var result = database.RunCommand<BsonDocument>(command); Console.WriteLine(result.ToJson());
var command = new BsonDocument("dbStats", 1); var result = await database.RunCommandAsync<BsonDocument>(command); Console.WriteLine(result.ToJson());
此命令的输出包括有关数据库中存储的数据的信息,如上一示例返回的结果所示:
{ "db" : "sample_restaurants", "collections" : 2, "views" : 0, "objects" : NumberLong(25438), "avgObjSize" : 548.95172576460413, "dataSize" : NumberLong(13964234), "storageSize" : NumberLong(8056832), "totalFreeStorageSize" : NumberLong(0), "numExtents" : NumberLong(0), "indexes" : 2, "indexSize" : NumberLong(1044480), "indexFreeStorageSize" : NumberLong(0), "fileSize" : NumberLong(0), "nsSizeMB" : 0, "ok" : 1 }
更多信息
有关本指南中概念的更多信息,请参阅MongoDB Server手册中的以下文档:
API 文档
要进一步了解本指南所讨论的任何方法或类型,请参阅以下 API 文档: