My document has some EmbeddedDocumentList and each of EmbeddedDocument should have autogenerated ObjectId(like _id) field because I will write query to get single EmbeddedDocument with this _id field.
How to reach that?
An ObjectId is a 12-byte BSON type hexadecimal string having the structure as shown in the example below. The first 4 bytes are a timestamp value, representing the ObjectId's creation, measured in seconds since the Unix epoch. Next 5-bytes represent a random value.
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.
ObjectId is one data type that is part of the BSON Specification that MongoDB uses for data storage. It is a binary representation of JSON and includes other data types beyond those defined in JSON. It is a powerful data type that is incredibly useful as a unique identifier in MongoDB Documents.
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.
Basically you can do it with following code
from mongoengine import *
from bson.objectid import ObjectId
class MyEmbeddedDocument(EmbeddedDocument):
oid = ObjectIdField(required=True, default=ObjectId,
unique=True, primary_key=True)
...
class MyDocument(Document):
embedded_list = EmbeddedDocumentListField(MyEmbeddedDocument)
...
Let explain more,
According to documentation you can add ObjectIdField to your models however it is not required and primary_key then you should set this attribute as True. Also, it do not generate ObjectId for each of it then import and set default it as ObjectId.
Last step is little bit tricky. If it is required explain,
bson.objectid.ObjectId is class that generate new objectids.
Moreover documentation say that default value can be callable than that explain clearly how it is work.
Also name of _id for embeddeddocument is not best naming practise beacuse you will write query for embeddeddocument with duble underscore and '_id' name have one more underscore as following code
MyDocument.objects.get(notice___id)
Then mongoengine throws exception beacuse of '_id' name have one more underscore. Thus you should give name as 'oid' as a short version of objectId or renname 'id' directly or what you want.
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