Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

mongodb

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.

like image 904
Efstathios Chatzikyriakidis Avatar asked Feb 20 '17 15:02

Efstathios Chatzikyriakidis


People also ask

How ObjectId is created in MongoDB?

ObjectID is automatically generated by the database drivers, and will be assigned to the _id field of each document. ObjectID can be considered globally unique for all practical purposes. ObjectID encodes the timestamp of its creation time, which may be used for queries or to sort by creation time.

What is the use of ObjectId in MongoDB?

MongoDB uses ObjectIds as the default value of _id field of each document, which is generated while the creation of any document. The complex combination of ObjectId makes all the _id fields unique.

Is MongoDB ObjectId unique?

The science behind MongoDB object IDs MongoDB is a NoSQL database that operates with collections and documents. Each document created on MongoDB has a unique object ID property. So when creating a document without entering an ID, the document will be created with an auto-generated ID.

What is the type of ObjectId in MongoDB?

Object ID is treated as the primary key within any MongoDB collection. It is a unique identifier for each document or record. Syntax: ObjectId(<hexadecimal>). An ObjectId is a 12-byte BSON type hexadecimal string having the structure as shown in the example below.


1 Answers

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();
    }

}
like image 91
Tinwor Avatar answered Sep 23 '22 12:09

Tinwor