【问题标题】:pymongo sort returning record that doesn't have the sorting keypymongo 排序返回没有排序键的记录
【发布时间】:2015-04-20 07:02:16
【问题描述】:

我正在对其日期列上的集合进行排序,以查找该集合中的最小日期。但是,它会返回我缺少日期键的记录。下面是sn-p。这是一个错误吗?

date_records = usercollection.find({'customer_id':'abc'}).sort('join_date',1).limit(1)
for record in date_records:
    print record # prints a record that doesn't have the join_date key
    print record['join_date']

输出:

{ "_id" : ObjectId("94dbe4c6ea890e28113d7664"), "region" : "Virginia", "country_code" : "US", "customer_id" : "abc"}

KeyError: u'join_date'

【问题讨论】:

  • 这不是错误。快速提问:您是否只想对包含 join_date 字段的记录进行排序?
  • 是的,我想从所有具有 join_date 字段的记录中检索最早的日期。

标签: python mongodb sorting pymongo


【解决方案1】:

这不是错误,sort in MongoDB 应该如何工作:

比较将不存在的字段视为空 BSON 目的。因此,对文档 { } 和 { a: null 中的 a 字段进行排序 } 会将文档按排序顺序视为等效。

而且,既然你已经注意到:

我想从所有 具有 加入日期字段

使用$exists检查join_date是否存在:

usercollection.find({
    'customer_id': 'abc',
    'join_date': {'$exists': True}
}).sort('join_date', 1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多