Home > Back-end >  How to db.getUser() using go mongo-driver
How to db.getUser() using go mongo-driver

Time:01-28

I want to get the user details for a db using go driver.

For ex. in mongoshell

> db.getUser("testuser")
null

How do i construct a bson.M or bson.D for this ?

I don't want to pass additional args just retrieve the userinfo of a db

var op bson.M
command := bson.D{{"getUser", 1}, {"username", "testuser"}}
err = clientInfo.Database(db).RunCommand(context.TODO(), cmd).Decode(&op)

I tried something like above but it was returning the below error:

(CommandNotFound) no such command: 'getUser'

What am I missing here?

CodePudding user response:

Database.RunCommand() is to facilitate calling MongoDB's runCommand() function, that is, it's a helper to run specified database commands.

That said, the getUser() function you call in the mongo shell is a function, not a command.

But there's a usersInfo command which gets you the same data. Its syntax is:

db.runCommand(
   {
     usersInfo: <various>,
     showCredentials: <Boolean>,
     showCustomData: <Boolean>,
     showPrivileges: <Boolean>,
     showAuthenticationRestrictions: <Boolean>,
     filter: <document>,
     comment: <any>
   }
)

This is how you can execute this usersInfo command:

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)

Note that the usersInfo document has various specifications, for example:

{ usersInfo: 1 }  

Returns information about the users in the database where the command is run. mongosh provides the db.getUsers() helper for this invocation of the command.

{ usersInfo: <username> }  

Return information about the a specific user that exists in the database where the command is run. mongoshprovides the db.getUser() helper for this invocation of the command.

{ usersInfo: { user: <name>, db: <db> } }  

Returns information about the user specified by the name and database.

{ usersInfo: [ { user: <name>, db: <db> }, ... ] }
{ usersInfo: [ <username1>, ... ] }

Returns information about the specified users.

{ forAllDBs: true }  

Returns information about users in all databases.

As you can see, the getUser() command is a shorthand for { usersInfo: <username> } which you can call like this:

var op bson.M
cmd := bson.D{{Key: "usersInfo", Value: "testuser"}}
err = clientInfo.Database(db).RunCommand(ctx, cmd).Decode(&op)

You can of course use an array if you want info about multiple users:

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