0

I have a collection in MongoDB of nested objects (basically a tree structure). I am trying to access certain "id" and "user_id" values in "children".

The collection looks like this: Image of a tree object in MongoDB

When I query "children" I get, e.g., this as output:

[{'children': [{'children': [{'children': [{'id': 737992252891537408, 'user_id': 3240396143}], 'id': 737991958161940480, 'user_id': 3240396143}], 'id': 737986305481682944, 'user_id': 56377143}], 'id': 737979183599652864, 'user_id': 3240396143}], 'id': 737978059291234304, 'user_id': 3240396143}]}

How do I efficiently access all the "id"'s with the 'user_id' = 56377143? I cannot seem to get all of them when it is nested too deep.

I tried using a for loop like this but it does not output all the 'id's which match the 'user_id's

val= "children"
lst_rt= []
lst_ids = []
def get_value(mydict, keys):

    if type(mydict) == dict:
        print(mydict[0]['user_id'], mydict[0]['id'], "TEST")
        return get_value(mydict[keys], val)
    if type(mydict) == list and keys in mydict[0] and mydict[0]['user_id'] == 56377143 :
        print(mydict[0]['id'],mydict[0]['user_id'],  'COND')
        return get_value(mydict[0][keys], val)
    elif mydict[0]['user_id'] == 56377143 and mydict[0]['id'] != None:
        print(mydict[0]['id'], mydict[0]['user_id'])
        lst_rt.append(int(mydict[0]['id']))
        return mydict[0]['id']



for x in root_tweets:

    print(get_value(x['children'], val))
  • Given your current data model: you can not. Imho, you [over-embed](https://blog.mahlberg.io/blog/2015/11/05/data-modelling-for-mongodb.html), which in this case transfers the workload to be done by MongoDB to your application. Have a deep look at [https://docs.mongodb.com/manual/applications/data-models-tree-structures/](https://docs.mongodb.com/manual/applications/data-models-tree-structures/). Depending on your use case, the materialized paths or the nested set "flavors" should do the trick. – Markus W Mahlberg Jun 21 '19 at 05:59
  • Just noticed that your workload most likely has to do something with social interaction. While this certainly can be modelled to work with MongoDB efficiently, it might well be worth looking into a graph database, which by far is better suited to express relations between objects. – Markus W Mahlberg Jun 21 '19 at 06:02

0 Answers0