dongyuan7981 2017-11-03 13:39
浏览 26
已采纳

golang mgo编组bson

I have a structure like this:

type data_to_store struct {
    Data     some_custom_structure       `json:"Data" bson:"Data"`
    MoreData   another_custom_structure   `json:"more_data" bson:"More_Data"`
}

creating an object that uses this struct:

Data := data_to_store {
    Data:     some_custom_struct_object,
    MoreData:   another_custom_struct_object,
}

And I'm trying to insert it into db like that:

session, _ := mgo.Dial("localhost")
defer session.Close()
session.SetMode(mgo.Monotonic, true)
collection := session.DB("test_database").C("test_collection")
collection.Insert(&Data)

And it does store, but it turns out to be inserted like this:

{ "lol": "rofl",
  "lmao": "kek",
  }
} { "blah": "blahblah",
  "ololo": 2,
}

Is there a way to make it be stored like the following?

"data": { "lol": "rofl",
  "lmao": "kek",
  }
}, "more_data" { "blah": "blahblah",
  "ololo": 2,
}

Marshalling data doesn't help in this endeavour, or I'm doing it wrong:

data, _ := bson.Marshal(&replay)
collection.Insert(&data)
  • 写回答

1条回答 默认 最新

  • dpbf62565 2017-11-03 13:52
    关注

    If this below is the Json structure that you want to store in Mongo:

    {
    "data": [{
            "lol": "rofl"
        },
        {
            "lmao": "kek"
        }
    ],
    "more_data": [{
            "blah": "blahblah"
        },
        {
            "ololo": 2
            }
        ]}
    

    You need these type of Go struct:

    type Data struct {
        Key  string `json:"key,omitempty"`
        Value string `json:"value,omitempty"`
    }
    
    type DataToStore struct {
       Data []Data `json:"data"`
       MoreData []Data  `json:"more_data"`
    }
    

    You can use this online tool to convert json into go struct.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)