登录
首页 >  Golang >  Go问答

使用 mongo-go-driver 执行与 shell 函数相同功能的操作

来源:stackoverflow

时间:2024-03-14 08:45:27 435浏览 收藏

“纵有疾风来,人生不言弃”,这句话送给正在学习Golang的朋友们,也希望在阅读本文《使用 mongo-go-driver 执行与 shell 函数相同功能的操作》后,能够真的帮助到大家。我也会在后续的文章中,陆续更新Golang相关的技术文章,有好的建议欢迎大家在评论留言,非常感谢!

问题内容

我正在使用 mongodb 驱动程序来检索数据 https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo 我试图解释()查询,但本文档没有提及任何相关内容。 如何通过 mongodb 驱动程序使用此功能? https://docs.mongodb.com/manual/reference/method/cursor.explain/

我想做一些类似于 go driver 的事情

db.col.find({filter:1}).explain("executionStats")

解决方案


我在 go 驱动程序源代码中没有看到任何实现解释的内容。

但是,您可以使用通用命令帮助程序(相当于 https://docs.mongodb.com/ruby-driver/master/tutorials/ruby-driver-database-tasks/#arbitrary-comands)自行发送解释命令。有关解释命令语法,请参阅 https://docs.mongodb.com/manual/reference/command/explain/。您需要根据您通常使用的查找查询手动构建查找命令,最简单的方法是使用命令监控来查看正在发送哪些命令。

例如,您可以使用 runcmd

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

本篇关于《使用 mongo-go-driver 执行与 shell 函数相同功能的操作》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>