使用mongo-go-driver执行shell函数(如explain())的方法是什么?

huangapple go评论110阅读模式
英文:

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

huangapple
  • 本文由 发表于 2021年2月25日 20:51:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/66368848.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定