3
votes

We are planning on using MongoDB _id as a key that we would provide to the client. Therefore, the requirement is that this key should not change if we ever need to move the data from one collection to another. The copy will be performed using db.copyDatabase() or mongoimport.

One of the ways in which data can be copied from one collection to another is iterating through the documents in the first collection(C1) and inserting these documents in the second collection(C2). In this case _id should remain the same(in C2) because it would be present in the documents(of C1) being inserted(same as the case in which we would provide an _id ourselves).

However, if there is an alternate way in which documents are copied, the _id might change since it depends on :

(1) The UNIX timestamp (2) Machine identifier (3) ProcessId

(**This should only happen if MongoDB while copying removes _id from documents in C1 and regenerated them while inserting into C2?)

We want the _id values to be same irrespective of the location of the destination collection: (1)within same database (2)different database - same machine (3)different database - different machine)

Thanks

1

1 Answers

10
votes

No, the _id numbers will not change.

A new ObjectId is generated when a document without an _id field is inserted into the database. When you insert a document which already has an _id field, MongoDB won't touch it.

The timestamp, machine identifier and processID refer to those where the ObjectID was generated. This can be a database server, but it can also be generated by the MongoDB driver on the application server. In that case MongoDB will not change it on its own.

By the way: The _id can be an auto-generated ObjectId, but it doesn't have to. You can also use any other value as _id, as long as you can guarantee that it's unique. So when your data already has a natural key, you can use this as _id when you want to.