给定 pymongo 中的开始和结束日期过滤日期时间数组

Filter an array of datetime given the start and end date in pymongo

我在 pymongo 上使用“$gte”和“$lte”过滤日期数组时遇到问题。我留给你一段代码来更好地理解这个问题。

import datetime
from pymongo import MongoClient
 

client = MongoClient('mongodb://localhost:27017')
db = client["AirQuality"]
demo = db["demo"]


demo.save({
    "devId": 1,
    "samples": [
        {"value":3, "datetime":datetime.datetime(2021, 3, 4, 20, 15, 22)},
        {"value":6, "datetime":datetime.datetime(2021, 3, 4, 22, 35, 12)},
        {"value":2, "datetime":datetime.datetime(2021, 3, 6, 10, 15, 00)}
    ]
})

我想过滤特定范围的值:

start = datetime.datetime(2021, 3, 4, 22, 00, 00)
end = datetime.datetime(2021, 3, 5, 2, 26, 49)
list(demo.find( { 'samples.datetime': {  "$gte":start, "$lte":end } } ))

输出结果如下:

[{'_id': ObjectId('604353efad253df2602dfaf9'), 'devId': 1, 'samples': [{'value': 3, 'datetime': datetime.datetime(2021, 3, 4, 20, 15, 22)}, {'value': 6, 'datetime': datetime.datetime(2021, 3, 4, 22, 35, 12)}, {'value': 2, 'datetime': datetime.datetime(2021, 3, 6, 10, 15)}]}]

但我预计:

[{'_id': ObjectId('604353efad253df2602dfaf9'), 'devId': 1, 'samples': [{'value': 6, 'datetime': datetime.datetime(2021, 3, 4, 22, 35, 12)}]}]

我哪里做错了?即使我对“值”应用过滤器也不起作用,所以我相信错误出在查询中!谢谢!

通过聚合解决:

result = demo.aggregate([
    {
    "$project": {
        "samples": {
            "$filter": {
                "input": "$samples",
                "as": "item",
                "cond": {  
                    "$and":[
                        { "$gte": [ "$$item.datetime", start ] }, 
                        { "$lte": [ "$$item.datetime", end ] }
                    ]}
            }
        }
    }
    }
])

list(result)

return:

[{'_id': ObjectId('604353efad253df2602dfaf9'), 'samples': [{'value': 6, 'datetime': datetime.datetime(2021, 3, 4, 22, 35, 12)}]}]

像这样使用我认为它可以解决您的问题:

list(demo.find( { "$and":['samples.datetime':{"$gte":start}, 'samples.datetime':{"$lte":end} ] } ))