这是我的mongodb文档,
{ "_id" : ObjectId("56c198f53869650eb0e2bc7a"), "Date" : ISODate("2016-02-15T14:50:14Z"), "nocontract" : 299039, "turnover" : 14882.65, "instrument" : "NSEFUT"}
{ "_id" : ObjectId("56c19ffe3869650eb0e2bc7b"), "Date" : ISODate("2016-02-15T15:20:45Z"), "nocontract" : 334464, "turnover" : 16650.6, "instrument" : "NSEFUT"}
{ "_id" : ObjectId("56c1a7073869650eb0e2bc7c"), "Date" : ISODate("2016-02-15T15:30:15Z"), "nocontract" : 351399, "turnover" : 17487.73, "instrument" : "NSEFUT"}
{ "_id" : ObjectId("56c1ae103869650eb0e2bc7d"), "Date" : ISODate("2016-02-15T15:30:15Z"), "nocontract" : 351401, "turnover" : 17487.84, "instrument" : "NSEFUT"}
{ "_id" : ObjectId("56c1b5183869650eb0e2bc7e"), "Date" : ISODate("2016-02-15T15:30:15Z"), "nocontract" : 351401, "turnover" : 17487.84, "instrument" : "NSEFUT"}
我需要查询对iso日期的尊重。当我提供10:00时,无论10:00我的数据库中有哪些记录,我需要通过python检索。 在这里,我写了代码:
from datetime import datetime, timedelta
from pymongo import MongoClient
conn = MongoClient("mongodb://localhost:27017")
db = conn.index
x = datetime.today()
off = 10
n = off + 1
y = x.replace(day=x.day, hour=off, minute=0, second=0, microsecond=0)
date1 = datetime(2016, 1, 15, off, 0, 0)
for r in db.turnover.find({ 'Date': {'$gte': date1, '$lt': y}}):
print r
但是当我尝试运行它时,它没有按照我的意愿提供正确的输出。任何人都可以帮我解决这个问题,因为我是python和mongodb的新手。
答案 0 :(得分:1)
这是你问题的答案,
from pymongo import MongoClient
from datetime import datetime
#make the mongodb connection to your localhost
conn=MongoClient("mongodb://localhost:27017")
db=conn['index']#connection to your database
r=[]
for doc in db['turnover'].find():
y=doc['time'].year
m=doc['time'].month
d=doc['time'].day
c=db['turnover'].find({"time":datetime(y,m,d,10,0,0)}).count()
if c>0:
a=db['turnover'].find({"time":datetime(y,m,d,10,0,0)})
for ele in a:
r2.append(ele)
print r