11

我正在尝试使用 Go 在 MongoDB 中插入一些数据。

这是数据结构:

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"`
}

这是我的插入功能:

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)
}

最后,这就是我所说的:

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)
}

问题是,我期待我的bson标签能神奇地工作,但事实并非如此。而不是将数据保存为:

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

它被保存为:

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

我怎样才能解决这个问题?

4

3 回答 3

15

将条目更改为:

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"`
}

结构标签的语法在标签之间不使用逗号。我相信这应该解决它。

于 2014-05-12T02:40:46.153 回答
8
type Entry struct {
    Id          bson.ObjectId `bson:"_id,omitempty" json:"id"`
    ResourceId  int           `json:"resource_id" bson:"resource_id"`
    Word        string        `json:"word"`
    Meaning     string        `json:"meaning"`
    Example     string        `json:"example"`
}

您可以使用 UpsertId 而不是 Count() 和 Insert() 来执行此操作,如果 Id 存在,则如果不插入则替换记录。

带有空 ObjectId 的 Insert() 让 MongoDB 处理 Id 分配。

编辑:误读了您的 Count 查询。你那里也有错误。它应该是“resource_id”而不是“resourceid”,因为您声明 bson 字段名为“resource_id”

于 2014-05-12T02:49:40.207 回答
0

将您的 Entry 结构更新为:

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

这应该工作!

于 2019-05-11T23:19:10.657 回答