从mongodb中连接两个结构体

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

Joining 2 structs from mongodb

问题

我有一个函数,使用.command来检索MongoDB管理员用户。

在下面的函数中,我有DbUsers结构体,并且我正在运行命令从两个不同的数据库中检索用户。

我的问题是,如何将这两个结果(adminUsers和externalUsers)合并后返回?它们具有相同的struct

type DbUsers struct {
    ...关于服务器的很多内容
    Users []Users 
}

type Users struct {
   User string
   ...很多内容
}

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 {
        panic(err)
    }

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

    //对于新手来说,不确定自己在做什么,但是这样做是不起作用的

    return []Users{adminUsers.Users, externalUsers.Users}
}
英文:

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 {
		panic(err)
	}

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

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


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

从mongodb中连接两个结构体

答案1

得分: 1

你可以这样做:

return append(adminUsers.Users, externalUsers.Users...)
英文:

You can do

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

huangapple
  • 本文由 发表于 2022年6月9日 17:18:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/72557733.html
匿名

发表评论

匿名网友

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

确定