Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define objectid in EmbeddedDocument with mongoengine?

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?

like image 550
Muhammed Hasan Celik Avatar asked Oct 28 '15 12:10

Muhammed Hasan Celik


People also ask

What is ObjectId How is it structured?

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.

What is an ObjectId?

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.

What datatype is ObjectId from MongoDB?

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.

What is the use of ObjectId?

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.


1 Answers

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.

like image 127
Muhammed Hasan Celik Avatar answered Sep 22 '22 10:09

Muhammed Hasan Celik