Python 根据时间条件在MongoDB集合中查找文档并写回时间戳?
我有一个数据库,其中的“accounts”集合如下:Python 根据时间条件在MongoDB集合中查找文档并写回时间戳?,python,mongodb,time,pymongo,Python,Mongodb,Time,Pymongo,我有一个数据库,其中的“accounts”集合如下: {u'timestamp': u'2016-06-09 23:29:50.083093', u'account': u'admin:password', u'_id': ObjectId('5766932f6f340ca9a70cdb16'), u'is_valid': u'True'} 我需要根据以下条件选择一个文档:if_valid为true,timestamp是否已超过24小时。因此,它应该是真实的并且当前时间2016-06-10 2
{u'timestamp': u'2016-06-09 23:29:50.083093', u'account': u'admin:password', u'_id': ObjectId('5766932f6f340ca9a70cdb16'), u'is_valid': u'True'}
我需要根据以下条件选择一个文档:if_valid为true,timestamp是否已超过24小时。因此,它应该是真实的并且当前时间2016-06-10 23:29:50.083093才能通过该条件。然后我必须用当前时间更新此文档的时间戳
我怎样才能做到这一点?我知道如何应用第一个条件:
import pymongo
from datetime import datetime
try:
conn=pymongo.MongoClient()
db = conn.instagram
collection = db.accounts
res = collection.find_one({"is_valid": "True"})
print res
except pymongo.errors.ConnectionFailure, e:
print "Could not connect to MongoDB: %s" % e
与作为参数传递的datetime
实例一起使用:
from datetime import datetime, timedelta
dt = datetime.now() - timedelta(hours=24)
res = collection.find_one({"is_valid": "True", "timestamp": {"$lt": dt}})
添加了“str”{“$lt”:str(dt)}})
,效果很好,谢谢!