簡體   English   中英

mongodb中的嵌套結構

[英]nested struct in mongodb

我使用以下軟件包:

“gopkg.in/mgo.v2”

“gopkg.in/mgo.v2/bson”

我嘗試處理一個嵌套結構,並將其放入mongodb中。 以下代碼可以正確完成工作,但是我不知道這是否正確。

// init
type DummyStruct struct {
    User     string  `bson:"user"`
    Foo      FooType `bson:"foo"`
}

type FooType struct {
    BarA int `bson:"bar_a"`
    BarB int `bson:"bar_b"`
}


//  main
foobar := DummyStruct{
    User: "Foobar",
    Foo: FooType{
        BarA: 123,
        BarB: 456,
    },
}

// Insert
if err := c.Insert(foobar); err != nil {
    panic(err)
}

是否需要分兩個部分來構建嵌套結構?

如果我使用json-> golang結構轉換器( https://mholt.github.io/json-to-go/

我將得到以下結構

type DummyStructA struct {
    User string `bson:"user"`
    Foo  struct {
        BarA int `bson:"bar_a"`
        BarB int `bson:"bar_b"`
    } `bson:"foo"`
}

現在我不知道如何填充該結構。

我嘗試了這個:

foobar := DummyStructA{
    User: "Foobar",
    Foo: {
        BarA: 123,
        BarB: 456,
    },
}

但出現此錯誤:復合文字中缺少類型

我也試過了

foobar := DummyStructA{
    User: "Foobar",
    Foo{
        BarA: 123,
        BarB: 456,
    },
}

並得到這2個錯誤:

  • 字段:值和值初始值設定項的混合

  • 未定義:Foo

還是有必要使用bson.M處理結構(DummyStructA)?

你可以這樣

package main

import (
    "fmt"
    "encoding/json"
)

type DummyStruct struct {
    User     string  `bson:"user" json:"user"`
    Foo      FooType `bson:"foo" json:"foo"`
}

type FooType struct {
    BarA int `bson:"barA" json:"barA"`
    BarB int `bson:"bar_b" json:"bar_b"`
}

func main() {
    test:=DummyStruct{}
    test.User="test"
    test.Foo.BarA=123
    test.Foo.BarB=321
    b,err:=json.Marshal(test)
    if err!=nil{
        fmt.Println("error marshaling test struct",err)
        return
    }
    fmt.Println("test data\n",string(b))
}

OutPut就是這樣

test data
{"user":"test","foo":{"barA":123,"bar_b":321}}

嘗試在游樂場玩耍: https : //play.golang.org/p/s32pMvqP6Y8

如果您在問題中定義2個不同的結構。 您需要像這樣聲明foobar

foobar := DummyStructA{
User: "Foobar",
Foo: FooType{
    BarA: 123,
    BarB: 456,
},

}

但是不必定義第二種類型來處理這種情況。 您可以使用類似以下的匿名struct

type DummyStructA {
    User string `bson:"user"`
    Foo struct{
       Name string `bson:"name"`
       Age int `bson:"age"`
    } `bson: "foo"`
}

但是在嘗試填充數據時變得很麻煩。

foobar := DummyStructA{
     User: "hello",
     Foo : struct{
           Name string
           Age int
         }{
         Name: "John",
         Age: 50,
     }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM