mongodb 地理空间查询

mongodb geospatial query

我有一个 mongodb 集合结构如下:

/* 1 */
{
  "_id" : ObjectId("551c53f3ecba12e015000045"),
  "nome" : "istituzione1",
  "username" : "username1",
  "email" : "some@email.it",
  "pwd" : "189bbbb00c5f1fb7fba9ad9285f193d1",
  "punti" : [{
      "punto_id" : ObjectId("551c5415ecba12e015000046"),
      "nome" : "ORACLE",
      "loc" : [-122.262168, 37.531595],
      "icona" : 2,
      "youtubelink" : "",
      "immagini" : [{
          "imgid" : ObjectId("551c5d3eecba12e015000084"),
          "contenttype" : "image/jpeg"
        }, {
          "imgid" : ObjectId("551c5d96ecba12e01500008a"),
          "contenttype" : "image/jpeg"
        }]
    }, {
      "punto_id" : ObjectId("551c5420ecba12e015000047"),
      "nome" : "GOOGLE\r\n",
      "loc" : [-122.083983, 37.422969],
      "icona" : 2,
      "youtubelink" : "",
      "immagini" : []
    }, {
      "punto_id" : ObjectId("551c5d74ecba12e015000089"),
      "nome" : "YAHOO",
      "loc" : [-122.025061, 37.428061],
      "icona" : 1,
      "youtubelink" : "",
      "immagini" : [{
          "imgid" : ObjectId("551c5da4ecba12e01500008e"),
          "contenttype" : "image/jpeg"
        }, {
          "imgid" : ObjectId("551c5daaecba12e015000092"),
          "contenttype" : "image/jpeg"
        }, {
          "name" : "Penguins.jpg",
          "imgid" : ObjectId("551c5dfeecba12e015000096"),
          "contenttype" : "image/jpeg"
        }]
    }]
}

我在 "punti" 内的 "loc" 数组上创建了一个 2d 索引,我正在尝试像这样进行地理空间查询:

db.istituzioni.find({ "punti.loc" : { $geoWithin : { $centerSphere : [ [ -121.931076, 37.364700 ], 14.5 / 6371 ] } } })

此查询应 return 仅 "punti" 的元素,字段 "nome" 设置为 "YAHOO"(我验证了此创建仅包含 "loc" 和 "nome" 字段),但它 return 是整个集合。
我尝试使用不同的 km 值,发现值 >= 10.9 km 时 return 是整个集合,而如果值 < 10.9 km 则查询 return 什么都没有。
我做错了什么?

查询return 文档,而不是文档中的数组元素。如果您只想查询 return punti 的一个元素,您应该更改您的文档结构或让另一个集合填充 punti 个元素。

您还可以在 return punti 数组的投影中使用 $ 位置运算符,仅使用匹配查询条件的第一个元素:

db.istituzioni.find(
    { "punti.loc" : { $geoWithin : { $centerSphere : [ [ -121.931076, 37.364700 ], 14.5 / 6371 ] } } },
    { "punti.$" : 1 }
)