type BookExt struct { ID bson.ObjectId `bson:"_id"` Title string `bson:"title"` SubTitle string `bson:"subTitle"` Author string `bson:"author"` }
以上结构体,在通过此结构体对象作为参数传入Insert插入文档时,必须通过bson.NewObjectId创建ID,如下代码所示:
aBook := BookExt{ ID:bson.NewObjectId(), Title: "Go", SubTitle: "Go", Author: "GoBj", } c.Insert(&aBook)
如果不想自己调用bson.NewObjectId,想让mongodb自动生成ID怎么办呢?有两种办法
1.使用bson.M构建
在使用mongodb插入文档传参的时候,可以用bson.M构建参数传入Insert
c.Insert(bson.M{ "title": "Go", "subTitle": "Go", "author": "GoBj", })
2.在结构体中,使用tag标签
type BookExt struct { ID bson.ObjectId `bson:"_id,omitempty"` Title string `bson:"title"` SubTitle string `bson:"subTitle"` Author string `bson:"author"` }
使用以上 `bson:"_id,omitempty"`标签,意思是当传入的_id是空时,将忽略该字段,所以当插入到mongodb时,发现此字段为空,mongodb将自动生成_id
还有一种标签方式也可以,如下:
type BookExt struct { ID bson.ObjectId `bson:"-"` Title string `bson:"title"` SubTitle string `bson:"subTitle"` Author string `bson:"author"` }
`bson:"-"`表示完全忽略此字段,但是也带来个问题,就是从mongodb查询时,使用此结构体作为返回参数,也会忽略此字段,结果中没有读出_id
所以推荐第一种标签方式.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。