Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb inserting doc without _id field

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: ...}
like image 775
Ramya Avatar asked Sep 11 '12 21:09

Ramya


People also ask

Is _id required in MongoDB?

In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field.

Why does MongoDB use _id?

Every document in the collection has an “_id” field that is used to uniquely identify the document in a particular collection it acts as the primary key for the documents in the collection. “_id” field can be used in any format and the default format is ObjectId of the document.

How manually insert data in MongoDB?

To insert data into MongoDB collection, you need to use MongoDB's insert() or save() method.


2 Answers

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.

like image 200
Stephane Godbillon Avatar answered Oct 04 '22 00:10

Stephane Godbillon


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.

like image 23
Sammaye Avatar answered Oct 04 '22 00:10

Sammaye