使用python查询mongodb



我在mongodb中使用pymongo python执行此查询:

cursor=mydb1.mongodbtime.find({"$and": [
{ "timestamp1": { "$gte":"2018-01-01 00:05:00 " } },
{ "timestamp1": { "$lte":"2018-01-02 00:05:00 " } }
]},
{"id13":1}
)
for x in cursor:
pprint(x)

在输出中它说

Process finished with exit code 0

但是我没有得到任何结果打印在我的屏幕上。也许我在查询中犯了一些错误。我的数据如下:

_id:ObjectId("603fb0b7142a0cbb439ae2e1")
id1:3758
id6:2
id7:-79.09
id8:35.97
id9:5.5
id10:0
id11:-99999
id12:0
id13:-9999
c14:"U"
id15:0
id16:99
id17:0
id18:-99
id19:-9999
id20:33
id21:0
id22:-99
id23:0
timestamp1:2010-01-01T00:05:00.000+00:00
timestamp2:2009-12-31T19:05:00.000+00:00

我用于时间戳的代码:

df['date4'] = df['date4'].astype('datetime64[ns]') #swsto gia mongodb
df['date2'] = df['date2'].astype('datetime64[ns]') #swsto gia mongodb
df['time3'] = df['time3'].apply(lambda x: datetime.datetime.strptime(x[0] + x[1] + ":" + x[2] + x[3], '%H:%M'))
df['time5'] = df['time5'].apply(lambda x: datetime.datetime.strptime(x[0] + x[1] + ":" + x[2] + x[3], '%H:%M'))
df['date2'] = df['date2'].apply(lambda x: arrow.get(x).format("YYYY-MM-DD"))
df['date4'] = df['date4'].apply(lambda x: arrow.get(x).format("YYYY-MM-DD"))
df['time3'] = df['time3'].apply(lambda x: arrow.get(x).format("HH:mm:ss"))
df['time5'] = df['time5'].apply(lambda x: arrow.get(x).format("HH:mm:ss"))
df['timestamp1'] = (df['date2'] + ' ' + df['time3']).astype('datetime64')
df['timestamp2'] = (df['date4'] + ' ' + df['time5']).astype('datetime64')
df.drop(['time3', 'time5', 'date2', 'date4'], axis=1, inplace=True)

您是否尝试过使用日期时间对象而不是字符串进行查询?

上面的时间戳后面有一个空格,可以包含在strptime

from datetime import datetime
cursor=mydb1.mongodbtime.find(
{"$and": [
{ "timestamp1": { 
"$gte": datetime.strptime("2018-01-01 00:05:00", "%Y-%m-%d %H:%M:%S") } 
},
{ "timestamp1": { 
"$lte":datetime.strptime("2018-01-02 00:05:00", "%Y-%m-%d %H:%M:%S") } }
]},
{"id13":1}
)
for x in cursor:
pprint(x)

对于信息,您不需要$and;这样也可以:

cursor=mydb1.mongodbtime.find({
"timestamp1": {"$gte": datetime.strptime("2018-01-01 00:05:00", "%Y-%m-%d %H:%M:%S"),
"$lte": datetime.strptime("2018-01-02 00:05:00", "%Y-%m-%d %H:%M:%S")}},
{"id13":1})

最新更新