【问题标题】:$near operator on a nested object list item嵌套对象列表项上的 $near 运算符
【发布时间】:2018-03-20 19:21:36
【问题描述】:

我有一个带有嵌套对象列表 (events) 的对象集合的 mongo db,如下所示:

{
    "_id" : ObjectId("59db84093f2fba2bf0bcfa90"),
    "progressStatus" : "NOT_STARTED",
    "events" : [ 
        {
            "issueDate" : ISODate("2017-10-09T00:00:00.000Z"),
            "eventType" : "xyz",
            "location" : {
                "point" : {
                    "type" : "Point",
                    "coordinates" : [ 
                        25.6011977000001, 
                        45.6579755
                    ]
                }
            },
            "cancelled" : false,
        }
    ]
}

尝试对事件使用$near$nearSphere 运算符进行查询。$.location:

{  
   "events":{  
      "$elemMatch":{  
         "eventType":"xyz",
         "$and":[  
            {  
               "cancelled":false
            },
            {  
               "location.point":{  
                  "$nearSphere":{  
                     "$geometry":{  
                        type:"Point",
                        coordinates:[  
                           25.601198,
                           45.657976
                        ]
                     },
                     "$maxDistance":20.4
                  }
               }
            }
         ]
      }
   }
}

这个查询给了我一个错误:

Error: error: {
    "waitedMS" : NumberLong(0),
    "ok" : 0,
    "errmsg" : "geoNear must be top-level expr",
    "code" : 2
}

应该怎么做?

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    neptune,这是因为使用 $nearSphere 的地理空间查询使用 geoNear 命令来获取文档,并且 geoNear 表达式(当命令运行时)需要位于查询的顶层。在您的示例中,它恰好处于低级别(在 elemMatch 内),在构造对 geoNear 的调用时引发错误。

    据我了解,您的 2dsphere 索引位于“events.location.point”上,对吗? 所以,你可以这样查询:

    db.sample6.find({"events": {$elemMatch: {$and: [{eventType: "xyz"},{cancelled: false}]}}, "events.location.point": {"$nearSphere": {"$geometry": {type: "Point", coordinates: [25.601198, 45.657976]}, "$maxDistance": 20.4}}})
    

    或者只是

    db.sample6.find({"events.eventType": "xyz", "events.cancelled": false, "events.location.point": {"$nearSphere": {"$geometry": {type: "Point", coordinates: [25.601198, 45.657976]}, "$maxDistance": 20.4}}})
    

    我认为最后一个更明智,因为它已经具有 AND 行为,不需要 $and 使用。此外,如果可能的话,在“位置”字段(如果它只包含坐标)上构建地理空间信息会更简洁和更少混乱(因为这些查询有很多括号和括号)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-15
      • 2012-02-03
      • 2013-02-10
      • 2018-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多