Reputation: 62596
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?
Upvotes: 9
Views: 9095
Reputation: 71
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'})
Upvotes: 7
Reputation: 18101
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')
Upvotes: 15