can't query over ListField(EmbeddedDocumentField)

点点圈 提交于 2019-12-07 13:29:13

问题


I have the following model

class Skill(EmbeddedDocument):
   name =  StringField(required = True)
   level = IntField(required = True)

class Agent(Document):
   name = StringField(required = True)
   email = EmailField(required = True, unique = True)
   skills = ListField(EmbeddedDocumentField(Skill))

I want to search for the Agents that have skills with (name = "computer skills and level >5)

I have wrote the following query:

 Agent.objects.filter(name='ashraf',  skills__level__gt=5,skills__name="Computer Skills")

If an Agent have skill named "Computer skills" with level = 3 and also have a skill named "English skills" with level = 10 this Agent will be in the query result


回答1:


You would need to do an $elemMatch[1] query and there is no inbuilt support for it in mongoengine at this time. You'd have to do a raw query like so:

Agent.objects.filter(
    name='ashraf',  
    __raw__={"skills": {
        "$elemMatch": {
            "level": {"$gt": 5}, 
            "name": "Computer Skills"
        }
    }}
)

[1] http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24elemMatch




回答2:


I don't use python driver, but the general Mongo syntax for what you're trying to accomplish is this....

db.agent.find({name:'ashraf', 'skills.name' : "computer skills", level:{ $gt: 5}})


来源:https://stackoverflow.com/questions/9241408/cant-query-over-listfieldembeddeddocumentfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!