I am using uMongo with Python 3.0 I have this model:
class Job(Document):
priority = IntField()
I'm using:
jobs = Job.find()
To get all jobs from mongo instance, and I am trying to sort them by priority.. but unfortunely, I can't seem to find the way to do it. I've searched the docs & googled it, tried bunch of things like
jobs = Job.find().sort('priority', 1)
jobs = Job.find().order_by('priority')
and lot of other solutions I found related to pymongo which doesn't work with uMongo.
but still stuck.. any help would be appreciated!
Thanks!
I have not used umongo
before, but upon examination, I found that the find() method actually returns a umongo.frameworks.pymongo.WrappedCursor
instance. And looking into the code it seems to me that this is just a pymongo.cursor with some goodies included. So, I did the following experiment and it worked. Please let me know if this helps or not.
1.> I created a collection called marketing
(Why this name? I do not know :) ) It looks like following
2.> As you can see that it is not ordered as per the priority field.
3.> Then I wrote the following code
In [1]: from datetime import datetime
In [2]: from pymongo import MongoClient
In [3]: from umongo import Instance, Document, fields, validate
In [4]: db = MongoClient().test_db
In [5]: instance = Instance(db)
In [6]: @instance.register
...: class Marketing(Document):
...: priority = fields.IntField()
...: class Meta:
...: collection = db.marketing
4.> Then I tried the normal for loop (without sorting)
In [8]: for doc in Marketing.find():
...: print(doc)
...:
<object Document __main__.Marketing({'id': ObjectId('5a1bf2acc24bf00f20acb2a2'), 'priority': 1})>
<object Document __main__.Marketing({'id': ObjectId('5a1bf2d1c24bf00f20acb2af'), 'priority': 3})>
<object Document __main__.Marketing({'id': ObjectId('5a1bf2e0c24bf00f20acb2b8'), 'priority': 2})>
<object Document __main__.Marketing({'id': ObjectId('5a1bf2eec24bf00f20acb2ba'), 'priority': 5})>
<object Document __main__.Marketing({'id': ObjectId('5a1bf2f4c24bf00f20acb2bc'), 'priority': 4})>
5.> Of course the documents are returned in the same order as they are present in the collection.
6.> Finally, I changed the for loop to sort the documents.
In [9]: import pymongo
In [11]: for doc in Marketing.find().sort([("priority", pymongo.ASCENDING)]):
...: print(doc)
...:
...:
<object Document __main__.Marketing({'id': ObjectId('5a1bf2acc24bf00f20acb2a2'), 'priority': 1})>
<object Document __main__.Marketing({'id': ObjectId('5a1bf2e0c24bf00f20acb2b8'), 'priority': 2})>
<object Document __main__.Marketing({'id': ObjectId('5a1bf2d1c24bf00f20acb2af'), 'priority': 3})>
<object Document __main__.Marketing({'id': ObjectId('5a1bf2f4c24bf00f20acb2bc'), 'priority': 4})>
<object Document __main__.Marketing({'id': ObjectId('5a1bf2eec24bf00f20acb2ba'), 'priority': 5})>
7.> As you can see, they are returned in the sorted order.
I am not 100% sure that this corresponds to your case or not. But from the question, it looks like.