Joining 2 structs from mongodb


I have a function that retrieve the mongodb admin users using .command

In the below function, I have the DbUsers struct, and I am running the command to retrieve the users from 2 different database.

My question is, how can I concat the 2 results (adminUsers & externalUsers) and return after merged? They are of the same struct.

type DbUsers struct {
    ...lots of stuff about the server
    Users []Users 

type Users struct {
   User string
   ...lots of stuff

func getUsers() Users {
    admin := CNX.Database("admin")
    external := CNX.Database("$external")

    command := bson.D{primitive.E{Key: "usersInfo", Value: 1}}

    var adminUsers DbUsers
    var externalUsers DbUsers
    err := admin.RunCommand(context.TODO(), command).Decode(&adminUsers)
    if err != nil {

    err2 := external.RunCommand(context.TODO(), command).Decode(&externalUsers)
    if err2 != nil {

    //New to Golang, not sure what I am doing but this doesn't work

    return []Users{adminUsers.Users, externalUsers.Users}

enter image description here


You can do

return append(adminUsers.Users, externalUsers.Users...)

Answered By – Gulshan

Answer Checked By – Terry (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.