【问题标题】:pymongo db query with multiple conditions- $and $exists具有多个条件的 pymongo db 查询 - $ 和 $exists
【发布时间】: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

【问题讨论】:

    标签: mongodb pymongo


    【解决方案1】:

    您正在尝试使用 Python 语法来表示数据结构的路径,但“数据库”希望它是使用“点表示法”的“键”的语法:

     cursor = self._collection.find({
       "Type": "f", 
       "runTime": { "$gte": model_dt_from, "$lte": model_dt_till },
       "data.PRICES SPOT.0": { "$exists": True }
     })
    

    你也不需要像这样写$and,因为所有的 MongoDB 查询条件都已经是 AND 表达式,而且你的部分语句实际上是这样做的,所以要保持一致。

    此外,“非空”数组的检查是 'data.PRICES SPOT.0' 额外的好处是您不仅知道它“存在”,而且它至少有一个要处理的项目

    Python 和 JavaScript 在对象/dict 构造方面几乎相同,因此您确实应该能够只遵循一般文档和此处的许多主要是 JavaScript 的示例。

    我个人甚至尝试在此处使用有效的 JSON 来标注答案,以便任何语言的用户都可以拾取和“解析”它。但是在这里,python 与您可以在mongo shell 中输入的内容完全相同。当然,True 除外。

    有关语法概述,请参阅 "Dot Notation",了解更多信息,请访问 Query on Embedded / Nested Documents

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-27
      • 2017-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-17
      相关资源
      最近更新 更多