0

I have the following entries in mongo db:

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

I need to find largest t for specific id

(assume test is collection and database names and specific id = 2)


In mongo client I need to run:

db.test.find( { '_id.id' : 2 } ).sort( { '_id.t' : -1} ).limit( 1 )

However, in pymongo, below doesn't work

from pymongo import MongoClient as mc
mc()['test']['test'].find( { '_id.id' : 2 } ).sort( { '_id.t' }, -1 )[0]

and raises:

TypeError: first item in each key pair must be a string

What should I do to get what I want using pymongo? Obviously, I can get everything and sort in python later, but that's wrong performance-wise

1
  • mc()['test']['test'].find( { '_id.id' : 2 }, sort = [ ( '_id.t', -1 )] )[0] or mc()['test']['test'].find_one( { '_id.id' : 2 }, sort = [ ( '_id.t', -1 )] ) seems to work Commented Apr 4, 2017 at 19:13

1 Answer 1

0

Python syntax is a little different than Javascript:

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

"sort" takes a list of pairs of (fieldname, direction).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.