简体   繁体   中英

Mongoengine: How to get one specific embedded document?

How can I get one specific embedded document eg by ID with mongoengine?

These are my models:

class Project(Document):
    project_name = StringField(unique=True, required=True)
    literature = ListField(EmbeddedDocumentField(Literature))

class Literature(EmbeddedDocument):
    id = ObjectIdField(required=True, default=ObjectId,
                        unique=True, primary_key=True, sparse=True)
    title = StringField()

and I want to get a specific Literature Object eg by the id "2".

I tried this:

literature = Project.objects(project_name=project_name).get(
        literature__id=2).literature

but this gives me all literature objects and not only the one with the ID "2"

I've also tried something like this:

literature = Project.objects.get(project_name=project_name).literature.filter(
        literature__id=2)

but this throws the error AttributeError: 'BaseList' object has no attribute 'filter'

so is there any way to get only that specific embedded document (literature with the ID= 2)? Dont know what else I could do

Cheers

When you are doing query, it will still point to specific Project document with liteature__id mentioned. You have to use filter for the query.

literature = Project.objects.filter(project_name=project_name,literature__id=id)

This will still point to Project object since you are doing query on Project and Literature is an embedded document inside it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM