博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
mongodb插入文档时不传ObjectId
阅读量:6984 次
发布时间:2019-06-27

本文共 1215 字,大约阅读时间需要 4 分钟。

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 所以推荐第一种标签方式.

转载于:https://www.cnblogs.com/zengyg/p/11008646.html

你可能感兴趣的文章
刷leetcode第705题- 设计哈希集合
查看>>
dubbo协议参考
查看>>
SpringAOP拦截Controller,Service实现日志管理(自定义注解的方式)
查看>>
读《白帽子讲Web安全》之安全意识篇(一)
查看>>
Session问题
查看>>
运用 autoconf 和 automake 自动生成 Makefile 实例讲解
查看>>
OpenSSL 之 RSA 相关命令学习笔记
查看>>
GLSL三种修饰符区别与用途(uniform,attribute和varying)
查看>>
python django django-debug-toolbar 加载缓慢,不能使用。
查看>>
操作系之进程调度及算法详解
查看>>
PHPexcel实列
查看>>
Butterknife 的简单使用 和 配合 Butterknife的插件 Zelezny
查看>>
Magento利用input type=”file”上传图片
查看>>
Android音频开发(4):如何存储和解析wav文件
查看>>
Handler延迟事件使用
查看>>
【DG】Oracle 19c使用dbca来搭建物理DG
查看>>
Cython安装
查看>>
StringBuilder 、StringBuffer 、 String
查看>>
brew install php55 报错 clang: error
查看>>
ubuntu18.4 安装swoole 和 php 扩展 swoole
查看>>