【问题标题】:How to sort compound index in pymongo [duplicate]如何在pymongo中对复合索引进行排序[重复]
【发布时间】:2017-08-30 03:20:23
【问题描述】:

我在 mongo db 中有以下条目:

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

我需要为特定的id找到最大的t

(假设test 是集合和数据库名称以及特定的id = 2


在 mongo 客户端我需要运行:

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 得到我想要的?显然,我可以稍后在 python 中获取所有内容并进行排序,但这在性能方面是错误的

【问题讨论】:

  • mc()['test']['test'].find( { '_id.id' : 2 }, sort = [ ( '_id.t', -1 )] )[0]mc()['test']['test'].find_one( { '_id.id' : 2 }, sort = [ ( '_id.t', -1 )] ) 似乎有效

标签: python mongodb pymongo


【解决方案1】:

Python 语法与 Javascript 略有不同:

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

"sort" 采用 (fieldname, direction) 对的列表。

【讨论】:

    猜你喜欢
    • 2018-07-25
    • 1970-01-01
    • 2015-04-17
    • 2021-09-02
    • 1970-01-01
    • 2018-09-22
    • 2017-04-28
    • 2010-11-15
    • 2018-05-26
    相关资源
    最近更新 更多