用Go将结构体have数组插入到Mongodb。

问题描述 投票:0回答:1

我想在MongoDB中插入如下的数据结构。

{ "rolecode": "DHBK1_ROLE_04", "functioncodelist": [ "DHBK1_FUNC_1", "DHBK1_FUNC_2", ..... "DHBK1_FUNC_n"] "productid": "ABC_Platform", "comid": "DHBK1" }

这是我的代码。

package main
import (
    "context"
    "gopkg.in/mgo.v2"
)


func main() {
    insertObj()
}
type CompanyRoleFunction struct {
    Rolecode         string `json:"rolecode"`
    Productid        string `json:"productid"`
    Functioncodelist []string
    Comid string `json:"comid"`
}
func insertObj() {
    session, err := mgo.Dial("mongodb://casuser:[email protected]:27017/users")
    if err != nil {
    panic(err)
    }
    c := session.DB("users").C("company_role_function")
    var companyRoleFunction CompanyRoleFunction
    companyRoleFunction.Rolecode = "DHBK1_ROLE_05"
    companyRoleFunction.Productid = "XYZ_Platform"
    companyRoleFunction.Comid = "DHBK1"
    err = c.Insert(companyRoleFunction)
    if err != nil {
        fmt.Println(err)
    }
}

我的代码已经运行,但它只插入了这样的结构(当然,因为我不知道如何处理数组Functioncodelist)。

[![在此输入图像描述][1]][1]

这是我的数据,我希望能插入

{"_id":{"$oid":"5ed0c2e2402a000037004c84"},"rolecode":"DHBK1_ROLE_07","functioncodelist":["DHBK1_FUNC_1","DHBK1_FUNC_2"],"productid":"ABC_Platform","comid":"DHBK1"}

go mgo
1个回答
0
投票

它没有在数据库中显示出来,因为你插入的文档没有包含任何值.在你的go代码中设置一个值,它应该会在数据库中显示出来,除非我误解了你的问题。

...
type Functioncode string
...
companyRoleFunction.Functioncodelist = make(map[string]Functioncode)
...
companyRoleFunction.Functioncodelist["foo"] = "bar"
...

请看 https:/tour.golang.orgmoretypes19 为快速介绍围棋地图。

© www.soinside.com 2019 - 2024. All rights reserved.