I am newbie to mongodb.
I need to insert a doc without the _id field generating automatically.
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: ...}
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.
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.
To insert data into MongoDB collection, you need to use MongoDB's insert() or save() method.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With