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

lllll
  • 37
  • 1
  • 5
  • `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 – lllll Apr 04 '17 at 19:13

1 Answers1

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).

A. Jesse Jiryu Davis
  • 23,641
  • 4
  • 57
  • 70