Field _id in Mongodb

The _id field is a field that it is populated as ObjectId or a unique value that we, as database administrator, asign to each document in a collection.

I have some doubts about this field:

  • If we use another field name as a collection key, could we simply delete it? I think no, because in the course says that this field always must exists.
  • If we, as admin, use a unique value but that it not the type object id, it will affect the sharding or maybe anything in the replication of nodes?
  • How could we define a key field that is not _id?

Thank you,

No you cannot remove the _id field.

Keys do not need to be ObjectID. They can be whatever you want.

It is called an index. It is covered in M201.

Hi @Antonio_Ubeda_Montero,

Here is some more information on this:

  • Some information on _id field.
  • How you can use unique index to maintain uniqueness on replica set and sharded cluster.

~ Shubham

Hi [Shubham_Ranjan],
¿Could you bring me a brief summary of what i must be in mind when i use a _id field with a type that it is not MongoDBObjectId (for instance an integer)?
Thank you

The following examples come to mind.

  1. In a calendar of events. Your _id might be the date while you have an array of events.

  2. In a fleet of cars, it could be the licence plate number or the VIN.

1 Like

Hi @Antonio_Ubeda_Montero ,

Hope you found @steevej-1495’s response helpful. It can be anything that can uniquely identify a document in the collection. Using MongoDB ObjectID inherently guarantees that every _id value in your collection is going to be unique but if you are using some other value for _id field then you must ensure it’s unique for each collection.

~ Shubham