简体   繁体   中英

Using django-mongodb, how to sort descending a capped collection?

Have this model, a class representing a capped collection at mongodb:

class Event(models.Model):
   objects = MongoDBManager()
   create_at = models.DateTimeField(auto_now_add=True)
   obj = BlobField()
   class MongoMeta:
      capped = True
      collection_size = 1000*1024*1024

What can I use to get the documents in the reverse order they are inserted?

I am not a python person but I can tell you that capped collections Natural Order is the order of insertion. Therefore you can just do the python equivalent of this to get the reverse order:

db.cappedCollection.find().sort({$natural:-1})

A bit of googling tells me this translates to something like the following in python:

 mongodb.cappedcol.find().sort('$natural',-1)

Or:

 mongodb.cappedcol.find().sort('$natural', pymongo.DESCENDING)

This is a temporal solution at pymongo level, not django-mongodb level:

from django.db import connections
import pymongo

conn = connections['default']
events_col = conn.get_collection('base_event')
events = events_col.find().sort('create_at', pymongo.DESCENDING)

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