Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform such filter queries in mongoengine on nested dicts or arrays contained in dict with python?

Tags:

python

mongodb

Say I have the following dict object:

{
    "a": "value of a",
    "somedict": {
        "someinfo": [
            {
                "name": "Jordan",
                "food": [
                    "fries",
                    "coke",
                    "drink"
                ]
            }
        ]
    }
}

If I wanted to apply a query filter in python using mongoengine, how would I do it? I see in the documentation you can do things like:

sample_objs_filter = Sample.objects(a='value of a')

But how would I filter on say

1) "name='Jordan'" 
2)'food' contains 'fries'?

If mongoengine cant do it, is there some other mongo library thats better at accomplishing this?

like image 294
Rolando Avatar asked Aug 09 '12 03:08

Rolando


2 Answers

I'd suggest reading more about mongodb's dot notation about how you can query / look into objects and return matching documents.

As you can't use a dot as a keyword argument mongoengine follows the django orm style of double underscores:

1) Sample.objects(somedict__someinfo__name='Jordan')
2) Sample.objects(somedict__someinfo__food='Fries')
like image 100
Ross Avatar answered Nov 03 '22 07:11

Ross


The mongoengine dot notation can be used within mongoengine in the following way: Sample.objects(__raw__ = "name_of_db_field.key":"value_to_match")

Say your class is:

Class data(Document):
   field = DictField(db_field="dbfield")

And your you store the dict:

{
    "a": "value of a",
    "somedict": {
        "someinfo": [
            {
                "name": "Jordan",
                "food": [
                    "fries",
                    "coke",
                    "drink"
                ]
            }
        ]
    }
}

The keys act as objects attributes, so can query as such:

data.objects(field__a = "value of a")

that reads the same as

data.objects(__raw__ = {'dbfield.a' : 'value of a'})

For nested items, the __ works as the dot. Example

data.objects(field__somedict__someinfo__name="Jordan")

reads the same as:

data.objects(__raw__ = {'dbfield.somedict.someinfo.name' : 'Jordan'})
like image 24
Rodrigo Domingues Avatar answered Nov 03 '22 05:11

Rodrigo Domingues