$box

运算符 $box 使用两个坐标对为地理空间查询定义矩形区域。 它可用于查找矩形地理边界内的位置。

语法

$box 运算符的语法如下:

{
  <location field>: {
    $geoWithin: {
      $box: [
        [<lower_left_longitude>, <lower_left_latitude>],
        [<upper_right_longitude>, <upper_right_latitude>]
      ]
    }
  }
}

参数

参数 DESCRIPTION
location field 包含地理空间数据的字段
lower_left 指定左下角的 [经度, 纬度] 数组
upper_right 指定右上角的 [经度, 纬度] 数组

示例:

stores使用集合,让我们在矩形区域中查找存储:

db.stores.find(
  {
    location: {
      $geoWithin: {
        $box: [
          [-142.0012, -51.3041],  // Lower left corner
          [123.3403, 70.1272]     // Upper right corner
        ]
      }
    }
  },
  {
    name: 1,
    location: 1
  }
).limit(2)

此查询返回属于这些坐标定义的矩形区域中的所有存储。

  {
    "_id": "923d2228-6a28-4856-ac9d-77c39eaf1800",
    "name": "Lakeshore Retail | Home Decor Hub - Franciscoton",
    "location": {
      "lat": 61.3945,
      "lon": -3.6196
    }
  },
  {
    "_id": "44fdb9b9-df83-4492-8f71-b6ef648aa312",
    "name": "Fourth Coffee | Storage Solution Gallery - Port Camilla",
    "location": {
      "lat": 78.3889,
      "lon": 0.6784
    }
  }