登录
首页 >  Golang >  Go问答

学习如何使用go的mongo-driver库中的db.getUser()方法

来源:stackoverflow

时间:2024-02-11 21:24:22 406浏览 收藏

Golang小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《学习如何使用go的mongo-driver库中的db.getUser()方法》带大家来了解一下##content_title##,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!


问题内容

我想使用 go 驱动程序获取数据库的用户详细信息。

例如。在 mongoshell 中

> db.getuser("testuser")
null

我如何为此构建 bson.m 或 bson.d ?

我不想传递额外的参数,只是检索数据库的用户信息

var op bson.m
command := bson.d{{"getuser", 1}, {"username", "testuser"}}
err = clientinfo.database(db).runcommand(context.todo(), cmd).decode(&op)

我尝试了类似上面的方法,但它返回了以下错误:

(CommandNotFound) no such command: 'getUser'

我在这里缺少什么?


正确答案


database.runcommand() 是为了方便调用mongodb的runcommand() 函数,即运行指定数据库命令的帮助器>.

也就是说,您在 mongo shell 中调用的 getuser() 函数是一个函数,而不是一个命令。

但是有一个 usersinfo 命令可以获取相同的数据。其语法为:

db.runcommand(
   {
     usersinfo: ,
     showcredentials: ,
     showcustomdata: ,
     showprivileges: ,
     showauthenticationrestrictions: ,
     filter: ,
     comment: 
   }
)

这是执行 usersinfo 命令的方法:

var op bson.m
cmd := bson.d{{key: "usersinfo", value: bson.m{
    "user": "testuser",
    "db":   "admin",
}}}
err = clientinfo.database(db).runcommand(ctx, cmd).decode(&op)

请注意,usersinfo 文档具有 各种规范,例如:

{ usersinfo: 1 }

返回有关运行该命令的数据库中的用户的信息。 mongosh 为该命令的调用提供 db.getusers() 帮助程序。

{ usersinfo:  }

返回有关运行该命令的数据库中存在的特定用户的信息。 mongosh 为该命令的调用提供 db.getuser() 帮助程序。

{ usersinfo: { user: , db:  } }

返回有关由名称和数据库指定的用户的信息。

{ usersinfo: [ { user: , db:  }, ... ] }
{ usersinfo: [ , ... ] }

返回有关指定用户的信息。

{ foralldbs: true }

返回有关所有数据库中用户的信息。

如您所见,getuser() 命令是 { usersinfo: } 的简写,您可以这样调用:

var op bson.m
cmd := bson.d{{key: "usersinfo", value: "testuser"}}
err = clientinfo.database(db).runcommand(ctx, cmd).decode(&op)

如果您想要有关多个用户的信息,您当然可以使用数组:

cmd := bson.D{{Key: "usersInfo", Value: []string{"testuser", "anotheruser"}}}

理论要掌握,实操不能落!以上关于《学习如何使用go的mongo-driver库中的db.getUser()方法》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

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