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 hexo+github部署博客
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?