2017-04-04 59 views
0

我在蒙戈分贝以下条目:如何排序pymongo复合索引

{ "_id" : { "t" : 1491329960, "id" : 2 } } 
{ "_id" : { "t" : 1491329961, "id" : 2 } } 
{ "_id" : { "t" : 1491329961, "id" : 3 } } 
{ "_id" : { "t" : 1491329961, "id" : 3 } } 

我需要找到最大t特定id

(假设test是收集和数据库的名称和具体id = 2


在蒙戈客户端我需要运行:

db.test.find({ '_id.id' : 2 }).sort({ '_id.t' : -1}).limit(1) 

然而,在pymongo,下面不工作

from pymongo import MongoClient as mc 
mc()['test']['test'].find({ '_id.id' : 2 }).sort({ '_id.t' }, -1)[0] 

,并提出:

TypeError: first item in each key pair must be a string 

我应该怎么做才能得到我想要使用pymongo?很显然,我可以得到一切,在蟒蛇再整理,但这是错误的性能代价

+0

'mc()['test'] ['test']。find({'_id.id':2},sort = [('_id.t',-1)])[0]' 或 'mc()['test'] ['test']。find_one({'_id.id':2},sort = [('_id.t',-1)])' 似乎工作 – lllll

回答

0

Python语法是不是JavaScript有一点不同:

find({ '_id.id' : 2 }).sort([('_id.t', -1)])[0] 

“排序”需要对列表(字段名,方向)。