douliang1369 2014-05-11 23:59
浏览 117
已采纳

使用mgo将数据插入MongoDB

I'm trying to insert some data in MongoDB using Go.

Here is the data struct:

type Entry struct {
    Id          string `json:"id",bson:"_id,omitempty"`
    ResourceId  int    `json:"resource_id,bson:"resource_id"`
    Word        string `json:"word",bson:"word"`
    Meaning     string `json:"meaning",bson:"meaning"`
    Example     string `json:"example",bson:"example"`
}

This is my insert function:

func insertEntry(db *mgo.Session, entry *Entry) error {
    c := db.DB(*mongoDB).C("entries")
    count, err := c.Find(bson.M{"resourceid": entry.ResourceId}).Limit(1).Count()
    if err != nil {
        return err
    }
    if count > 0 {
        return fmt.Errorf("resource %s already exists", entry.ResourceId)
    }
    return c.Insert(entry)
}

And finally, this is how I call it:

entry := &Entry{
    ResourceId:  resourceId,
    Word:        word,
    Meaning:     meaning,
    Example:     example,
}
err = insertEntry(db, entry)
if err != nil {
    log.Println("Could not save the entry to MongoDB:", err)
}

The trouble is, I was expecting my bson tags to magically work, but they don't. Instead of data being saved as:

{ "_id" : ObjectId("53700d9cd83e146623e6bfb4"), "resource_id" : 7660708, "word" : "Foo" ...}

It gets saved as:

{ "_id" : ObjectId("53700d9cd83e146623e6bfb4"), "id" : "", "resourceid" : 7660708, "word" : "Foo"...}

How can I fix this?

  • 写回答

3条回答 默认 最新

  • dsd30433 2014-05-12 02:40
    关注

    Change entry to:

    type Entry struct {
        Id          string `json:"id" bson:"_id,omitempty"`
        ResourceId  int    `json:"resource_id" bson:"resource_id"`
        Word        string `json:"word" bson:"word"`
        Meaning     string `json:"meaning" bson:"meaning"`
        Example     string `json:"example" bson:"example"`
    }
    

    The syntax for Struct Tags does not use commas between tags. I believe this should fix it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配