我正在使用$geoNear
和near
在 MongoDB 的聚合内部。我已将 MongoDB 数据库托管到 mlabs。并且在我的本地一切正常,但不知道为什么当我部署应用程序时出现以下错误:
block 引用>"geoNear command failed: { ok: 0.0, errmsg: \"more than one 2dsphere index, not sure which to run geoNear on
下面是我使用过的代码:
Shops.aggregate([ { $geoNear: { near: { type: "Point", coordinates: coordinates }, distanceField: "dist.calculated", maxDistance: 80467, spherical: true } } ]) .then((products)=>{ res.json(products); })
有人可以帮我做同样的事情吗?
最佳答案
如错误消息所示,这是因为您有多个 2dsphere
索引,因此 $geoNear
不知道该使用哪一个。
在这种情况下,您可以:
- 删除第二个地理索引,或者
- 使用 $geoNear documentation 中提到的
key
参数:
If your collection has multiple 2d and/or multiple 2dsphere indexes, you must use the key option to specify the indexed field path to use. Specify Which Geospatial Index to Use provides a full example.
文档中也提到了该错误:
If there is more than one 2d index or more than one 2dsphere index and you do not specify a key, MongoDB will return an error.
您可以使用db.collection.getIndexes()列出集合上定义的所有索引。
以下是使用 key
参数的示例:
> db.test.insert([
{_id:0, loc1:{type:'Point',coordinates:[1,1]}, loc2:{type:'Point',coordinates:[2,2]}},
{_id:1, loc1:{type:'Point',coordinates:[2,2]}, loc2:{type:'Point',coordinates:[1,1]}}
])
然后我创建两个 2dsphere
索引:
> db.test.createIndex({loc1:'2dsphere'})
> db.test.createIndex({loc2:'2dsphere'})
在不指定key
的情况下运行$geoNear
将输出错误:
> db.test.aggregate({$geoNear:{near:{type:'Point',coordinates:[0,0]},distanceField:'d'}})
...
"errmsg": "more than one 2dsphere index, not sure which to run geoNear on",
...
使用 key: loc1
将根据 loc1
索引对结果进行排序(_id: 0
位于 _id: 1
):
> db.test.aggregate(
{$geoNear: {
near: {type: 'Point',coordinates: [0,0]},
distanceField: 'd',
key: 'loc1'}})
{ "_id": 0, "loc1": { "type": "Point", "coordinates": [ 1, 1 ] }, "loc2": { "type": "Point", "coordinates": [ 2, 2 ] }, "d": 157424.6238723255 }
{ "_id": 1, "loc1": { "type": "Point", "coordinates": [ 2, 2 ] }, "loc2": { "type": "Point", "coordinates": [ 1, 1 ] }, "d": 314825.2636028646 }
并且,使用 key: loc2
将根据 loc2
索引对结果进行排序(_id: 1
位于 _id: 0
):
> db.test.aggregate(
{$geoNear: {
near: {type: 'Point',coordinates: [0,0]},
distanceField: 'd',
key: 'loc2'}})
{ "_id": 1, "loc1": { "type": "Point", "coordinates": [ 2, 2 ] }, "loc2": { "type": "Point", "coordinates": [ 1, 1 ] }, "d": 157424.6238723255 }
{ "_id": 0, "loc1": { "type": "Point", "coordinates": [ 1, 1 ] }, "loc2": { "type": "Point", "coordinates": [ 2, 2 ] }, "d": 314825.2636028646 }
关于node.js - 多个 2dsphere 索引,不确定要运行 geoNear 中的哪一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56562394/