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?
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')
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'})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With