Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: update dictionary in document

I have a MongoDB document that saves occurrences of some things in a dictionary:

{
  "id" : 1,
  "occurrences" : {
    "1" : 1,
    "2" : 5,
    "17" : 1,
    "35" : 4
  }
}

I now want to add or update some entries, for example add a "12:3" to the occurrences, or update the number of occurrences of "17" to 2, so let's say as an example I want to add {"12":3} and {"17":2} to this dictionary. It is driving me crazy because I simply can not get it to work. I could use arrays and all that, but I would really like to have it in this particular design. Any ideas on how to solve this? I tried so many different things with $set and $each and so on.

like image 531
konse Avatar asked Mar 25 '15 22:03

konse


1 Answers

I wrote a function to convert a dictionary to a new dictionary which only updates fields in that dictionary:

def convert_2_dict_mongodb(obj):
    result = {}
    for key, val in obj.items():
        if not isinstance(val, dict):
            result[key] = val
            continue

        for sub_key, sub_val in val.items():
            new_key = '{}.{}'.format(key, sub_key)
            result[new_key] = sub_val
            if not isinstance(sub_val, dict):
                continue

            result.update(convert_2_dict_mongodb(result))
            if new_key in result:
                del result[new_key]

    return result

Example:

abc = {
    'a': 1,
    'b': {
        'x': 1,
        'y': 2,
        'z': {
            'g': 1,
            'h': {
                'e': [1, 2, 3]
            }
        }
    },
    'h': {
        'a': [1, 2, 3]
    }
}

To:

{'h.a': [1, 2, 3], 'b.x': 1, 'b.z.h.e': [1, 2, 3], 'b.z.g': 1, 'a': 1, 'b.y': 2}
like image 185
Trong Pham Avatar answered Sep 28 '22 05:09

Trong Pham