如何自定义mongo查询比较ru

2024-10-01 01:33:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些日期相似的数据:

  2013-03-26 05:33:15
  2013-03-26 16:48:39
  ...

我不想用默认的Date()方式将它们与我的查询进行比较。因为我只想知道白天是否匹配(小时:分钟+/-10分钟)。你知道吗

例如,如果我查询05:28:15,它应该返回包含“2013-03-26 05:33:15”的条目

我一直在尝试使用关键字“customizemongodb query”查找一些提示,但没有得到任何结果。你知道吗

我想知道这是可能的还是有其他选择。你知道吗


Tags: 数据date方式条目关键字query小时customizemongodb
2条回答

我会花你想要的时间来查找和减去/添加你的公差,并使用范围进行搜索:

from datetime import datetime, timedelta
from pymongo import MongoClient
client = MongoClient('localhost', 27017)

# Test Data
client.test.times.remove()
client.test.times.insert({ 'date': datetime(2013,03,26,05,33,15)})
client.test.times.insert({ 'date': datetime(2013,03,26,16,48,39)})


def get_approx_datetime(dt):
    start = dt-timedelta(minutes=10)
    end = dt+timedelta(minutes=10)
    return (start,end)


find_date = datetime(2013,03,26,05,28,15)
(start,end) = get_approx_datetime(find_date)


for time in client.test.times.find({ 'date': { '$gt': start, '$lt': end} }):
    print time

输出:

{u'date': datetime.datetime(2013, 3, 26, 5, 33, 15), u'_id': ObjectId('517cb34f1d41c806aec7c4ad')}

您可以使用$where子句查找小时和分钟范围内的所有匹配项。例如,我们要匹配05:28+/-10分钟:

client.collection.times.find({"$where": "this.Date.getHours() == 5 && this.Date.getMinutes() >= 18 && this.Date.getMinutes() <= 38"})

相关问题 更多 >