mongodb

mongodb-query

mongodb-java

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

Solution 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.

Solution 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.

Solution 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" : ... } )

Solution 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).

Solution 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