What's the difference between:
{
_id: ObjectId("507f191e810c19729de860ea")
}
and
{
_id: "507f191e810c19729de860ea"
}
I can't seem to find anything on the matter.
It puzzles me because when you insert using JavaScript it'll use the ObjectId("507f191e810c19729de860ea")
format.
But if you use the C# driver it'll use the "507f191e810c19729de860ea"
format.
The string format seems like the better choice as it uses less space.
“_id” field can be used in any format and the default format is ObjectId of the document. An ObjectID is a 12-byte Field Of BSON type. The first 4 bytes representing the Unix Timestamp of the document. The next 3 bytes are the machine Id on which the MongoDB server is running.
A MongoDB ObjectId is a 12-byte UUID can be used as a HEX string representation with 24 chars in length.
An ObjectID is a unique, not null integer field used to uniquely identify rows in tables in a geodatabase. ObjectIDs are limited to 32-bit values, which store a maximum value of 2,147,483,647.
The _id field in MongoDB document database is considered to be the default field for BSON ObjectId's and it is, by default, indexed. _id and id are not the same. You may also prefer to add a field called id if you want, but it will not be index unless you add an index.
ObjectIDs are a 12-byte BSON object ID (it requires 24 to display as hex, since you need two hex characters to encode a byte value). The string is a full 24 bytes. See the ObjectID specification for specifics.
That said, you can use anything you want for your _id
field, but it's recommended that you stick to a consistent scheme - either use all strings (as well as strings in cases that you reference other documents from foreign keys) or use all ObjectIDs. It is conventional to use ObjectIDs, but as long as you have a fully consistent scheme, you shouldn't have significant problems with it.
The biggest difference is of course the destination storage and how you interact with it in the API. (I wrote about something similar here on StackOverflow as it related to DBRefs).
When using the C# driver (and plain-old-C#-objects), if you want to force the Id to be stored as an ObjectId
, you may need to use the BsonRepresentationAttribute
:
public class StackOverflow
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public string Name { get; set; }
}
Or if you want to keep your classes free of MongoDB attributes:
BsonClassMap.RegisterClassMap<StackOverflow>(cm => {
cm.AutoMap();
cm.IdMemberMap.SetRepresentation(BsonType.ObjectId);
});
I have used this technique a number of times successfully. When I don't explicitly set the _id
to a custom ID (a custom key of some sort), I always use the ObjectId
format as it's relatively small and unique (and is smaller than a UUID and also embeds creation time which is really nice sometimes).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With