英文:
Execute shell functions like explain() with mongo-go-driver
问题
我正在使用MongoDB驱动程序检索数据https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo
我试图使用explain()函数解释查询,但是这份文档没有提到相关内容。
我该如何在MongoDB驱动程序中使用这个函数?https://docs.mongodb.com/manual/reference/method/cursor.explain/
我想在Go驱动程序中做类似的事情
db.col.find({filter:1}).explain("executionStats")
英文:
I'm using MongoDB driver to retrieve data https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo
I was trying to explain() the query but this documentation doesn't mention anything related.
How can I use this function with the MongoDB driver? https://docs.mongodb.com/manual/reference/method/cursor.explain/
I want to do something like with Go Driver
db.col.find({filter:1}).explain("executionStats")
答案1
得分: 1
我在Go驱动程序源代码中没有看到任何实现解释的内容。
但是,你可以使用通用命令助手自己发送解释命令(相当于https://docs.mongodb.com/ruby-driver/master/tutorials/ruby-driver-database-tasks/#arbitrary-comands)。请参阅https://docs.mongodb.com/manual/reference/command/explain/了解解释命令的语法。你需要手动构建从通常使用的查找查询中的查找命令,最简单的方法是使用命令监视来查看发送的命令。
英文:
I don't see anything in Go driver source that implements explain.
However, you can send the explain command yourself using the generic command helper (equivalent of https://docs.mongodb.com/ruby-driver/master/tutorials/ruby-driver-database-tasks/#arbitrary-comands). See https://docs.mongodb.com/manual/reference/command/explain/ for the explain command syntax. You would need to manually construct the find command from the find query you normally use, easiest way to do this is to use command monitoring to see what commands are being sent.
答案2
得分: 1
你可以使用RunCmd,例如
func ExampleDatabase_RunCommand() {
var db *mongo.Database
// 运行一个解释命令,查看在集合“bar”上执行“find”时的查询计划,指定ReadPreference选项以显式设置读取首选项为primary。
findCmd := bson.D{{"find", "bar"}}
command := bson.D{{"explain", findCmd}}
opts := options.RunCmd().SetReadPreference(readpref.Primary())
var result bson.M
err := db.RunCommand(context.TODO(), command, opts).Decode(&result)
if err != nil {
log.Fatal(err)
}
fmt.Println(result)
}
英文:
you can use RunCmd, for example
func ExampleDatabase_RunCommand() {
var db *mongo.Database
// Run an explain command to see the query plan for when a "find" is
// executed on collection "bar" specify the ReadPreference option to
// explicitly set the read preference to primary.
findCmd := bson.D{{"find", "bar"}}
command := bson.D{{"explain", findCmd}}
opts := options.RunCmd().SetReadPreference(readpref.Primary())
var result bson.M
err := db.RunCommand(context.TODO(), command, opts).Decode(&result)
if err != nil {
log.Fatal(err)
}
fmt.Println(result)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论