ubh
ubh

Reputation: 607

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

I am sorting through a collection on it's date column to find the minimum date in that collection. However, it returns me a record where the date key is missing. Below is the snippet. Is this a bug?

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']

Output:

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

KeyError: u'join_date'

Upvotes: 1

Views: 89

Answers (1)

alecxe
alecxe

Reputation: 473773

This is not a bug and how sort in MongoDB is supposed to work:

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.

And, since you've noted:

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

check for join_date to exist using $exists:

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

Upvotes: 2

Related Questions