MongoEngine / MongoEngine/mongoengine

Problem update dictionaries with a high degree of nesting using DynamicDocument

Open
#1,038 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Bug ListField
Dominant language
Python
Stars
4.3k
Forks
1.2k
Avg merge
4h 41m
Merged PRs (30d)
11

Description

I try to repeat this:

In [1]: from mongoengine import *

In [2]: class TestData(DynamicDocument): pass

In [3]: td = TestData()

In [4]: td.mydata = [{'name':'bob','sdata':[]}]

In [5]: td.save()
Out[5]: <TestData: TestData object>

At this example we created new dynamic document.
Next we want to get this document and append some data to 'sdata' key in dictionary.

In [6]: td2 = TestData.objects.first()

In [7]: td2.mydata
Out[7]: [{'name': 'bob', 'sdata': []}]

In [8]: td2.mydata[0]['sdata'].append({'office':'current'})

In [9]: td2.mydata
Out[9]: [{'name': 'bob', 'sdata': [{'office': 'current'}]}]

In [10]: td2.save()
Out[10]: <TestData: TestData object>

Let's get this document again and check our changes

In [11]: td3 = TestData.objects.first()

In [12]: td3.mydata
Out[12]: [{'name': 'bob', 'sdata': []}]

As you can see mongoengine not saved new values in 'sdata' key

I found a solution how to get around this problem

In [13]: from copy import copy

In [14]: td4 = TestData.objects.first()

In [15]: ddd = copy(td4.mydata)

In [16]: ddd
Out[16]: [{'name': 'bob', 'sdata': []}]

In [17]: ddd[0]['sdata'].append({'office':'current'})

In [18]: ddd
Out[18]: [{'name': 'bob', 'sdata': [{'office': 'current'}]}]

In [19]: td4.mydata = copy(ddd)

In [20]: td4.save()
Out[20]: <TestData: TestData object>

In [21]: td5 = TestData.objects.first()

In [22]: td5.mydata
Out[22]: [{'name': 'bob', 'sdata': [{'office': 'current'}]}]

But this is not the right way.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the nested-list update shown with DynamicDocument and MongoDB, then trace how the in-place append is tracked between loading and save. Done means appending to td2.mydata[0]['sdata'] persists after reloading the document, with a regression test covering the example.

Written by the indexing model from the issue text.

Assessment

Tech stack
mongodb, python
Domain
databases
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.