本文介绍了如何构建并传递bson文档 - Go lang?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的项目中使用和mongoDB,用于连接 MongoDB

I am using Go and mongoDB in my project and mgo is to connect to connect MongoDB.

我是有以下文件将被插入到MongoDB中:

I am having following document this is to be inserted in the MongoDB

 {
     "_id" : ObjectId("53439d6b89e4d7ca240668e5"),
     "balanceamount" : 3,
     "type" : "reg",
     "authentication" : {
       "authmode" : "10",
       "authval" : "sd",
       "recovery" : {
          "mobile" : "sdfsd",
          "email" : "[email protected]"
        }
      },
     "stamps" : {
        "in" : "x",
        "up" : "y"
     }
  }

我已经创建了如上所述的BSON文档。

I have created the BSON document as above.

我有两个软件包


  1. account.go

  1. account.go

dbEngine.go


  • dbEngine.go

    帐户。 go 用于创建BSON文档并将BSON文档发送到dbEngine.go

    account.go is used to create BSON document and send the BSON document to dbEngine.go

    dbEngine.go 用于建立连接到MongoDB并插入文档。
    ,同时将BSON文档传递给dbEngine.go

    dbEngine.go is used to establish connection to MongoDB and insert the document.while passing BSON document to dbEngine.go

    dbEngine.Insert(bsonDocument);

    dbEngine.Insert(bsonDocument);

    dbEngine.go我有方法

    In dbEngine.go i am having method

    func Insert(document interface{}){
     //stuff
    }
    



    BSON文档中是否使用interface {}。

    Whether interface{} is not to be used for BSON document.

    我是 Go 的新手。任何建议或帮助将不胜感激

    I am new to Go. Any suggestion or help will be grateful

    推荐答案

    您不需要自己生成BSON文档。 b在account.go中说一下,你将拥有一个账户struct:

    You don't need to generate a BSON document yourself.
    Let say in account.go you will have an account struct:

    type Account struct {
      Id bson.ObjectId `bson:"_id"` // import "labix.org/v2/mgo/bson"
      BalanceAmount int
      // Other field
    }
    

    然后在dbEngine.go中插入函数:

    Then in dbEngine.go your Insert function:

    func Insert(document interface{}){
      session, err := mgo.Dial("localhost")
      // check error
      c := session.DB("db_name").C("collection_name")
      err := c.Insert(document)
    }
    

    然后,在您的应用程序中的某处:

    And then, some where in your app:

    acc := Account{}
    acc.Id = bson.NewObjectId()
    acc.BalanceAmount = 3
    
    dbEngine.Insert(&acc);
    

    这篇关于如何构建并传递bson文档 - Go lang?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

  • 08-26 02:42