10

I'm have a huge documents in a collection. I want to remove auto generated Object Id (_id key) from all the documents and replace it with another field as a Primary key?

I don't understand is why is there a need for a default Object Id in first place?

linthum
  • 333
  • 1
  • 8
  • 22

2 Answers2

4

In mongodb each document must be unique, so you need an unique field to be used as id. If you do not provide one, mongodb will provide one for you automatically. However, if you want to give custom ids for whichever reason (improve query performance being one of them), you can do it manually. Here goes my suggestions:

If you are inserting a new document, you can manually set the _id field like:

doc._id = "12312312" //(Or whichever function to generate id you have)
doc.save(...)

But when you already have a document in the database, you cannot modify it anymore. What you can do is to make a copy of the document, save a new document with the same data and erase the old one:

// Fetch the documents
docs = db.clients.find({})

docs.forEach((doc) => {
   //For each field you copy the values
   new_doc.field = doc.field
   new_doc._id = //YOUR ID FUNCTION 

   // insert the document, using the new _id
   db.clients.insert(new_doc)

   // remove the document with the old _id
   db.clients.remove({_id: doc._id})
}

This question is similar to the following one:

How update the _id of one MongoDB Document?

Hope my answer was helpful

Community
  • 1
  • 1
Israel Zinc
  • 2,713
  • 2
  • 18
  • 30
  • 1
    This does not answer the question. The question is about wheter it is possible to remove the _id field and use another field as primary key, not about changing the _id value. – Douglas Henrique Feb 12 '18 at 23:56
3

It is not possible to remove the _id field.

From https://docs.mongodb.com/manual/core/document/#the-id-field:

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.

What you can do is name your primary key as _id.

Douglas Henrique
  • 327
  • 4
  • 10
  • If I'm understanding correctly, we can set `_id` to whatever we want, but we cannot change `_id` to say `student_id`? Is that correct? – DUDANF Dec 11 '19 at 13:55
  • This answer needs to be confirmed with links... Because Mongo must let us change the default primary mainly to avoid duplications of indexes if I want another custom key. – Philip Enc Jun 08 '20 at 12:17