使用mgo向MongoDB插入数据

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

我该如何解决这个问题?

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

结构体标记的语法不使用逗号分隔标记。我认为这应该可以解决它。


这是错误的。Id需要是bson.ObjectId类型,而且除了ResourceId之外,bson标签都不是必需的,因为ResourceId不会自动转换为"resource_id"。mgo会将大写结构字段转换为小写。只需要json小写字段名即可。 - user2312578
1
@dalu _id 实际上可以是任何类型。编辑:除非问题的提问者期望一个 ObjectId,这在问题中并不完全清楚。 - Gustavo Niemeyer
@dalu 正如Gustavo所说,_id不需要是ObjectId,这是默认值,但并不总是必需的选择。此外,没有任何问题。我个人认为,在长期实践中包括bson结构标签是更好的做法,即使它是相同的。想象一下,如果未来的开发人员决定将变量“Word”更改为“Title”,而没有定义bson标记,他们将在不知不觉中更改数据存储。在我看来,保留bson标记有助于后续维护,并且在最坏的情况下,为了清晰起见,让您多输入几个字符。 - TrevorSStone

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分配。

编辑: 错误理解了您的计数查询。 您还有一个错误。 应该是“resource_id”,而不是“resourceid”,因为您声明bson字段的名称为“resource_id”。


insertEntry 的工作方式可能看起来有些违反直觉,但它符合程序的工作方式。 - if __name__ is None
是的,我已经更正了。我以为你是在检查objectId是否存在,然后插入新记录。 - user2312578
1
那是正确的答案。ID 需要是 bson.ObjectId。 - user2312578
如果我们不插入对象ID,Mongo将创建一个默认的“_id”参数。 - Himanshu

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

这应该可以工作!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接