1

I have a specific kind of JSON which I need to code into a model for my Django problem. Problem is I have nested document in it or should I say object of objects and I don't know how to design the model in Pymodm or Mongoengine.

Here is the JSON schema on which I am working.

{
    "something": "something",
    "safasf": 5,
    "key": {
        "value1": ["dsd", "dd"],
        "value2": {
            "blah1": "blahvalue1",
            "blah2": "blahvalue2"
        }
    }
}

I have already looked into the documentation and API References of both these ODMs. I could not find anything useful. At best they have fields.EmbeddedDocumentListField which stores list of documents/objects.

1 Answers1

1

Your sample json is quite meaningless but this is an example of how you could model it with mongoengine

from mongoengine import *

class MyNestedDoc(EmbeddedDocument):
    value1 = ListField(StringField())
    value2 = DictField(StringField())

class MyDocument(Document):
    something = StringField()
    safasf = IntField()
    key = EmbeddedDocumentField(MyNestedDoc)


nested_doc = MyNestedDoc(
    value1=["dsd", "dd"],
    value2={
        "blah1": "blahvalue1",
        "blah2": "blahvalue2"
    }
)
doc = MyDocument(something="something", safasf=5, key=nested_doc)
doc.save()

This will save in Mongo an object with the following shape

{'_id': ObjectId('5d2d832c96d2914c2a32c1b3'),
 'key': {
  'value1': ['dsd', 'dd'],
  'value2': {
    'blah1': 'blahvalue1',
    'blah2': 'blahvalue2'
    }
  },
 'safasf': 5,
 'something': 'something'
}
bagerard
  • 5,681
  • 3
  • 24
  • 48
  • I posted this JSON as a sample only. Thanks for your answer but I always need 'blah1' and 'blah2' keys in 'value2' and someone can add other keys in 'value2' but I don't want that. – Prashant Goyal Jul 16 '19 at 08:19
  • And I have a very deep and nested JSON Schema which is to be forced. I just want to know is there any other way than keep making nested documents one after another? – Prashant Goyal Jul 16 '19 at 08:58
  • DictField let anyone add key to the object, if your structure is known in advance then you should use EmbeddedDocumentField and define explicitely all the fields. I used both in my example to show the 2 pattern provided by mongoengine – bagerard Jul 16 '19 at 13:52