使用mgo将数据插入MongoDB

if *_*one 11 go mongodb mgo

我正在尝试使用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"`
}
Run Code Online (Sandbox Code Playgroud)

这是我的插入功能:

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)
}
Run Code Online (Sandbox Code Playgroud)

最后,这就是我所说的:

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)
}
Run Code Online (Sandbox Code Playgroud)

麻烦的是,我期待我的bson标签神奇地工作,但他们没有.而不是将数据保存为:

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

它被保存为:

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

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

Tre*_*one 14

将条目更改为:

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"`
}
Run Code Online (Sandbox Code Playgroud)

Struct Tags的语法不在标记之间使用逗号.我相信这应该解决它.


小智 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"`
}
Run Code Online (Sandbox Code Playgroud)

您可以使用UpsertId代替Count()和Insert(),如果存在Id,则记录将被替换,如果没有插入则.

带有空ObjectId的Insert()允许MongoDB处理Id赋值.

编辑:误读您的计数查询.你也有错误.它应该是"resource_id"而不是"resourceid",因为您声明bson字段名为"resource_id"