Mongodb inserting doc without _id field

让人想犯罪 __ 提交于 2019-12-17 18:42:19

问题


I am newbie to mongodb.

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

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

how to do it?

something like this

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

回答1:


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

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 }

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

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.




回答2:


The _id field is the default key for a mongo document unless you are using capped collections.

It is an umutable field which cannot be left out of a document structure.

I would recommend using tennant_id as _id instead.




回答3:


Mongodb will automatically generate the '_id' field only if you do not specify a value for the '_id' field when you insert a document. So you can just manually set the _id when you insert the document:

db.tenants.insert( {"_id" : 123, "Tenant_info" : ... } )



回答4:


Every MongoDB document must have a unique field "_id" and if you don't provide it then it will be automatically generated for you.

It is not possible to rename this field.

Your two choices are:

1) ignore the generated _id field and use your own tenant_id field (you will need to add a unique index on that field) or 2) store tenant_id value in the _id field (and take advantage of the fact that it already has a unique index on it).




回答5:


There is no way to remove _id field in any mongodb collections. As, @stephene said,I tried the same, but iam getting error like this

> db.noautoid._mongo.insert(db.noautoid._fullName, {name: "Jack"});
 2015-06-18T11:22:29.149+0530 E QUERY    Error: insert needs 3 args
 at (shell):1:20


来源:https://stackoverflow.com/questions/12378320/mongodb-inserting-doc-without-id-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!