Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoengine get latest()

In django how to get latest instance of a query set if i'm using MongoEngine

Normally we do

Users.objects.latest('id')

But i cant use latest in MongoEngine.

;) . i'm in stuck .

I didn't find a solution here . but i've implemented . whats your opinion about below

Users.objects.all().order_by('-id').limit(1)[0] 

This will return the latest instance .

and also fixed the issue by committing it to mongoenngine.

https://github.com/anishmenon/mongoengine/

You may install this and use

 Users.objects.latest('id')
like image 999
Anish Menon Avatar asked Mar 20 '14 11:03

Anish Menon


People also ask

How do I update MongoEngine?

MongoEngine provides the following methods for atomic updates on a queryset. update_one() − Overwrites or adds first document matched by query. update() − Performs atomic update on fields matched by query. modify() − Update a document and return it.

Which is better PyMongo or MongoEngine?

Both PyMongo and MongoEngine can be used to access data from a MongoDB database. However, they work in very different ways and offer different features. PyMongo is the MongoDB recommended library. It makes it easy to use MongoDB documents and maps directly to the familiar MongoDB Query Language.

What is the difference between PyMongo and MongoEngine?

PyMongo is the low-level driver wrapping the MongoDB API into Python and delivering JSON in and out. MongoEngine or other layers like MongoKit map your MongoDB-based data to objects similar to native Python database drivers + SQLAlchemy as ORM.


2 Answers

You could do:

Users.objects.order_by('-id').first()
like image 120
Ross Avatar answered Oct 01 '22 04:10

Ross


Ross's answer is great enough.

But if you really need a latest(), implementing a custom QuerySet can do this.

"Decorator" way:

class Users(Document):
    username = StringField()

    @queryset_manager
    def latest(doc_cls, queryset):
        return queryset.order_by('-id').first()

"meta" way:

class UsersQuerySet(QuerySet):

    def latest(self):
        return self.order_by('-id').first()

class Users(Document):
    meta = {'queryset_class': UsersQuerySet}

Now you can:

Users.objects.latest()
# or
Users.latest()
like image 20
Lake Chan Avatar answered Oct 01 '22 03:10

Lake Chan