mongodb mongoengine filter document on nexted EmbeddedDocumentLIst fields

本秂侑毒 提交于 2021-01-29 15:23:10

问题


I have a document with a EmbeddedDocumentList inside an other EmbeddedDocumentlist, I need to filter the collections retrieving only the documents that have a specified value for a field inside the inner EmbeddedDocumentList the reduced version of my models is:

class RecipeIngredient(EmbeddedDocument):
    ingredient = ReferenceField(Ingredient, required=True)
    quantity = IntField(required=True)

class RecipeLocalData(EmbeddedDocument):
    price = FloatField(required=True)
    enabled = BooleanField(default=False)
    materialAvailable = BooleanField(default=True)
    ingredients = EmbeddedDocumentListField(RecipeIngredient)

class Recipe(Document):
    localData = EmbeddedDocumentListField(RecipeLocalServerData)
    name = StringField(required=True, unique=True)
    deleted = BooleanField(default=False)

this is a sample of documents stored in the collectiosn

 {
 "_id" : ObjectId("55acf8229d5544137f46b2d9"),
"localData" : [
    {
        "price" : NumberLong("14112312313"),
        "enabled" : true,
        "rank" : 12,
        "materialAvailable" : true,
        "ingredients" : [
            {
                "ingredient" : ObjectId("5591948c9d5544c7bd68502e"),
                "quantity" : 1
            }
        ]
    }
],
"name" : "p1",
"deleted" : false,
}

directly on mongodb Im able to achieve this result with the query

db.recipe.find({"localData.ingredients.ingredient":ObjectId("5591948c9d5544c7bd68502e")})

using mongoengine I'm try do query in that way:

Recipe.objects.filter(localData__ingredients__ingredient=ingredient)

Recipe.objects.filter(localData__ingredients__ingredient=ingredient.id)

or using raw pymongo query

Recipe.objects(__raw__={"localData.ingredients.ingredient":document.id})

but is not working there is some other option instead of filtering at application level?

来源:https://stackoverflow.com/questions/31519280/mongodb-mongoengine-filter-document-on-nexted-embeddeddocumentlist-fields

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