Sajith Kumar Ganesan
Sajith Kumar Ganesan

Reputation: 574

How to get a document for a particular timestamp in Mongodb?

I have the following set of document info in my collection and how to get one document with a particular timestamp?

As this timestamp is in ISODate(), how to pass the same from my pyMongodb client?

[
{
    "_id" : ObjectId("5f64658a64b79fed80b8e4df"),
    "time" : ISODate("2020-09-18T13:15:14.290Z"),
    "details" : "with all details",
    "type" : "general",
    "payLoad" : {
        "myname" : "nameofme",
    }
},
{
    "_id" : ObjectId("5f64658a64b79fed80b8e4df"),
    "time" : ISODate("2020-09-18T13:18:20.290Z"),
    "details" : "with all details",
    "type" : "general",
    "payLoad" : {
        "myname" : "nameofme",
    }
},
{
    "_id" : ObjectId("5f64658a64b79fed80b8e4df"),
    "time" : ISODate("2020-09-18T13:50:20.290Z"),
    "details" : "with all details",
    "type" : "general",
    "payLoad" : {
        "myname" : "nameofme",
    }
}
]

Upvotes: 0

Views: 40

Answers (1)

Belly Buster
Belly Buster

Reputation: 8844

Construct it using a datetime object:

from datetime import datetime
from pymongo import MongoClient

db = MongoClient()['mydatabase']

dt = datetime(2020, 9, 18, 13, 15, 14, 290000)

print(list(db.mycollection.find({"time" : dt})))

gives:

[{'_id': ObjectId('5f64658a64b79fed80b8e4dd'), 'time': datetime.datetime(2020, 9, 18, 13, 15, 14, 290000), 'details': 'with all details', 'type': 'general', 'payLoad': {'myname': 'nameofme'}}]

Upvotes: 1

Related Questions