Mongodb插入没有_id字段的文档 [英] Mongodb inserting doc without _id field

查看:37
本文介绍了Mongodb插入没有_id字段的文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 mongodb 的新手.

I am newbie to mongodb.

  1. 我需要插入一个不自动生成 _id 字段的文档.

  1. I need to insert a doc without the _id field generating automatically.

我需要将字段 Tenant_id 设置为唯一或需要将_id"字段更改为 Tenant_id.

I need to set the field Tenant_id as unique or need to change the "_id" field to Tenant_id.

怎么做?

类似的东西

     Tenant
        {Tenant_id: 123, Tenant_info: ...}

推荐答案

默认情况下,所有常规集合如果不存在 _id 字段,则会自动插入该字段.

By default, all regular collections automatically insert an _id field if it is absent.

但是,可以在创建集合时更改此行为,方法是将 autoIndexId 参数显式设置为 false.

However, this behavior can be changed when you create the collection, by setting explicitely the autoIndexId parameter to false.

> db.createCollection("noautoid", { autoIndexId: false })
{ "ok" : 1 }

然后你可以插入没有_id字段的文档.但是一些驱动程序,例如 javascript 驱动程序(以及 mongo 控制台),会自行添加 _id 字段.在 mongo 控制台中,您可以这样做:

Then you can insert documents without _id field. But some drivers, like the javascript one (and so the mongo console), add the _id field by themselves. In the mongo console, you can do this:

> db.noautoid._mongo.insert(db.noautoid._fullName, {name: "Jack"})
> db.noautoid.find()
{ "name" : "Jack" }

有关 autoIndexId 字段的更多信息可以在 MongoDB 文档中找到.此页面是关于封顶集合,但 autoIndexId 字段对于常规集合和封顶集合都是通用的.

More information about the autoIndexId field can be found in the MongoDB documentation. This page is about Capped Collections but the autoIndexId field is common to both regular and capped collections.

这篇关于Mongodb插入没有_id字段的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆