【发布时间】:2018-11-02 14:51:28
【问题描述】:
示例文档如下所示
{
"_id":ObjectId("562e7c594c12942f08fe4192"),
"Type": "f",
"runTime": ISODate("2016-12-21T13:34:00.000+0000"),
"data" : {
"PRICES SPOT" : [
{
"value" : 29.64,
"timeStamp" : ISODate("2016-12-21T23:00:00.000+0000")
},
{
"value" : 29.24,
"timeStamp" : ISODate("2016-12-22T00:00:00.000+0000")
},
{
"value" : 29.81,
"timeStamp" : ISODate("2016-12-22T01:00:00.000+0000")
},
{
"value" : 30.2,
"timeStamp" : ISODate("2016-12-22T02:00:00.000+0000")
},
{
"value" : 29.55,
"timeStamp" : ISODate("2016-12-22T03:00:00.000+0000")
}
]
}
}
我的 MongoDb 有不同的 Type 文档,我想为所有文档获取光标,这些文档来自 type: "f" 但实际存在的 时间范围。数据库中有一些文件破坏了我之前的代码(没有检查PRICES SPOT是否存在)。
我看到我可以使用documentation 中的$and 和$exists。但是,由于范围和嵌套,我无法设置它。我正在使用 pyMongo 作为我的 python 驱动程序,并且还注意到 here 我必须将 $and 和 $exists 括在引号中。
我的代码
def grab_forecast_cursor(self, model_dt_from, model_dt_till):
# create cursor with all items that actually exist
cursor = self._collection.find(
{
"$and":[
{'Type': 'f', 'runTime': {"$gte": model_dt_from, "$lte": model_dt_till}
['data']['PRICES SPOT': "$exists": true]}
]})
return cursor
这导致Key Error 找不到data。没有PRICE SPOT 的示例文档看起来与我在开始时发布的完全一样,只是分别没有。
简而言之.. 有人可以帮我设置一个查询,在该查询中我可以抓取具有特定类型的所有文档但实际上嵌套了尊重内容的光标。
更新
我在model_dt_till 之后添加了一个逗号,现在有一个语法错误。
def grab_forecast_cursor(self, model_dt_from, model_dt_till):
# create cursor with all items that actually exist
cursor = self._collection.find(
{
"$and":[
{'Type': 'f', 'runTime': {"$gte": model_dt_from, "$lte": model_dt_till},
['data']['PRICES SPOT': "$exists": true]}
]})
return cursor
【问题讨论】: