Mongodb inserting doc without _id field

Ramya picture Ramya · Sep 11, 2012 · Viewed 27.6k times · Source

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: ...}

Answer

Stephane Godbillon picture Stephane Godbillon · Sep 12, 2012

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.