I'm updating a document with an array of embedded documents, directly in Mongo shell. I would like each of these sub-docs to have an _id
field, but these are not created automatically as they are for top-level documents. Is there a way to simply create an new ObjectId in Mongo shell? Something along the lines of (below example is not valid):
"prop": [
{
"_id": new ObjectId(), // creates the objectId when executing the line
"foo": "bar"
}
]
The main requirement is not having to manually generate random strings for each doc to create. Is that possible?
MongoDB uses ObjectIds as the default value of _id field of each document, which is generated during the creation of any document. 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>).
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.
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. The next 2 bytes are of process id. The last Field is 3 bytes used for increment the objectid.
If you want to ensure that MongoDB does not create the _id Field when the collection is created and if you want to specify your own id as the _id of the collection, then you need to explicitly define this while creating the collection. When explicitly creating an id field, it needs to be created with _id in its name.
Yes it is possible. You can generate ObjectId
ObjectId id = new ObjectId();
// or this
ObjectId id = ObjectId.get();
Then it can be used for update doc. Hope it helps.
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