_id field is reserved for primary key in mongodb, and that should be a unique value. If you don't set anything to _id it will automatically fill it with "MongoDB Id Object". But you can put any unique info into that field.
One way of achieving this behaviour is by setting the value to _id (which is reserved for a primary key in MongoDB) field based on the custom fields you want to treat as primary key.
i.e. If I want employee_id as the primary key then at the time of creating document in MongoDB; assign _id value same as that of employee_id.
In mongodb _id field is reserved for primary key. Mongodb use an internal ObjectId value if you don't define it in your object and also create an index to ensure performance.
But you can put your own unique value for _id and Mongodb will use it instead of making one for you. And even if you want to use multiple field as primary key you can use an object:
{ _id : { a : 1, b: 1} }
Just be careful when using object as ids, the order of keys (a and b in the example) matters, if you swap them, it is considered a different id.
db.< collection >.createIndex( < key and index type specification>, {
unique: true } )
Let's take that our database have collection named student and it's document have key named student_id which we need to make a primary key. Then the command should be like below.