harry
harry

Reputation: 31

Get latest Document with respect to (time or Id) using Pymongo only

In MongoDB, this technique is commonly used to obtain the latest document with respect to (time or ID):

 db.collection.find().sort({ "_id": -1 }).limit(1);

 MySchema.find().sort({ _id: -1 }).limit(1)

db.getLastInsertedDocument.find({}).sort({_id:-1}).limit(1);

But when I use pymongo to find the latest entry in my collection the code below gives an error.

from pymongo import MongoClient

import random
import datetime
import time
import pprint
from datetime import datetime
#from bson import ObjectId

client = MongoClient()
client = MongoClient('localhost', 27017)
db = client.sensor_temperature # createdb
posts = db.posts2
print('Total Record for the collection: ' + str(posts.count()))

x=datetime.now().strftime("%H:%M:%S")

record=posts.find().sort({ "_id": -1 }).limit(1)  ###  ERR
#record=posts.find({"start_date":new Date()}).pretty() ####  ERR
#record=posts.findOne({"_id": x}) #### <pymongo.cursor.Cursor object at 0x0141FCD0>
pprint.pprint(record)
text=record
print(text)

How to get the latest records using Pymongo only?

Upvotes: 0

Views: 58

Answers (1)

Belly Buster
Belly Buster

Reputation: 8814

Some of the pymongo driver commands don't match exactly to the mongodb shell. The documentation explains the method calls. This should work:

from pymongo import MongoClient, DESCENDING
<...>
record=posts.find().sort('_id', DESCENDING).limit(1)
pprint.pprint(list(record)[0])

Upvotes: 0

Related Questions