簡體   English   中英

pymongo沒有排序鍵的排序返回記錄

[英]pymongo sort returning record that doesn't have the sorting key

我正在其日期列上對集合進行排序,以查找該集合中的最小日期。 但是,它為我返回了缺少日期鍵的記錄。 以下是代碼段。 這是錯誤嗎?

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'

這不是錯誤,也不應該在MongoDB中進行sort

比較將不存在的字段視為空的BSON對象。 這樣,對文檔{}和{a:null}中的a字段進行排序將按排序順序將文檔視為等效。

而且,由於您已經注意到:

我想從所有具有join_date字段的記錄中檢索最早的日期

使用$exists檢查join_date是否$exists

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM