gpt4 book ai didi

python - pymongo排序返回没有排序键的记录

转载 作者:行者123 更新时间:2023-12-01 04:50:28 26 4
gpt4 key购买 nike

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

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'

最佳答案

这不是一个错误以及如何sort in MongoDB应该可以工作:

The comparison treats a non-existent field as it would an empty BSON Object. As such, a sort on the a field in documents { } and { a: null } would treat the documents as equivalent in sort order.

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

I want to retrieve the earliest date from all records that have the join_date field

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

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

关于python - pymongo排序返回没有排序键的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28597829/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com