Search code examples
c#mongodb

Use ObjectId.GenerateNewId() or leave MongoDB to create one?


In C# I can use the ObjectId.GenerateNewId() to generate ObjectId values.

Most of the time when I insert a document in a collection I do not set the value of _id fields. MongoDB creates the ObjectId values automatically.

I would like to ask if it is safe to set it manually by using the ObjectId.GenerateNewId() method.


Solution

  • When you insert a new mongodb document the son driver check if exist a property with the BsonId AttributeClass. If exist and is null it create a new ObjectId, if doesn't exist during the document insertion mongodb will generate e new ObjectId.
    Sometimes users encounter problem with "only zero" ObjectId, for this reason my suggestion is to use a combination of BsonID attribute class and ObjectId.GenerateNewId so you are sure that that property will not have weird behaviour.
    e.g.

    public class SomeClass {
    
        [BsonId]
        public ObjectId MySuperId { get; set; }
    
        public SomeClass() {
            this.MySuperId = ObjectId.GenerateNewId();
        }
    
    }