简体   繁体   中英

How to get a document by its primary key in mongoengine?

I'm porting an application from App Engine's ndb to mongoengine. ndb provides the Model.get_by_id method, and I'd like to implement this in terms of mongoengine. So how do you get a document by its automatically generated id, or by whatever field has primary_key set to True?

You can use with_id() :

class MyDocument(Document):
    ...
    @classmethod
    def get_by_id(cls, id):
        return cls.objects.with_id(id)

This will return the document instance if it exists or None if it doesn't.

Check out http://docs.mongoengine.org/guide/querying.html

Answer is simple:

Model.objects(id='your-id')

I presume that you know the name of the primary key field.

Use with_id . It's specialized for that purpose.

Model.objects.with_id('your-id')

It returns None if no object is found.

But ensure you're not setting filter (as if it was filter method ) because it raises InvalidQueryError .

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