对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。

命令监控

本指南向您展示如何使用 Go 驱动程序监控驱动程序发送到 MongoDB 部署的命令的结果。

您可以使用有关应用程序中命令事件的信息来了解查询性能的变化或解决瓶颈。

您可以通过在应用程序中订阅命令事件来访问有关命令事件的详细信息。 以下示例演示了如何通过实例化CommandMonitor并连接到部署来订阅CommandStartedEvent事件:

var eventArray []*event.CommandStartedEventcmdMonitor := &event.CommandMonitor{ Started: func(ctx context.Context, e *event.CommandStartedEvent) { eventArray = append(eventArray, e) },}clientOpts := options.Client().ApplyURI(uri).SetMonitor(cmdMonitor)client, err := mongo.Connect(context.TODO(), clientOpts)

您可以订阅以下一个或多个命令监控事件:

事件名称
说明

CommandStartedEvent

在命令启动时创建。

CommandSucceededEvent

命令成功时创建。

CommandFailedEvent

命令不成功时创建。

以下部分显示了每种类型的命令监控事件的输出示例。

*event.CommandStartedEvent{ "Command": "...", "DatabaseName": "...", "CommandName": "...", "RequestID": ..., "ConnectionID": "...", "ServerConnectionID": ..., "ServerConnectionID64": ..., "ServiceID": "..."}
*event.CommandSucceededEvent{ "DurationNanos": 38717583, "Duration": 38717583, "CommandName": "insert", "RequestID": 13, "ConnectionID": "...", "ServerConnectionID": ..., "ServerConnectionID64": ..., "ServiceID": null, "Reply": "..."}
*event.CommandFailedEvent{ "DurationNanos": 38717583, "Duration": 38717583, "CommandName": "insert", "RequestID": 13, "ConnectionID": "...", "ServerConnectionID": ..., "ServerConnectionID64": ..., "ServiceID": null, "Failure": "..."}

要了解有关监控 MongoDB 部署的更多信息,请参阅如何监控 MongoDB一文。

要了解有关执行 MongoDB 操作的更多信息,请参阅CRUD 操作指南。

要进一步了解本指南所提及的方法和类型,请参阅以下 API 文档: