我在 MongoDB 中使用$geoNear和near在聚合内。我已将我的 MongoDB 数据库托管到 mlabs 中。并且在我的本地一切正常,但不知道为什么当我部署我的应用程序时出现以下错误:
"geoNear 命令失败:{ ok: 0.0, errmsg: \"多个 2dsphere 索引,不确定在哪个上运行 geoNear
以下是我使用的代码:
Shops.aggregate([
{
$geoNear: {
near: {
type: "Point",
coordinates: coordinates
},
distanceField: "dist.calculated",
maxDistance: 80467,
spherical: true
}
}
])
.then((products)=>{
res.json(products);
})
Run Code Online (Sandbox Code Playgroud)
任何人都可以帮助我吗?
正如错误消息所示,这是因为您有多个2dsphere索引,所以$geoNear不知道该使用哪一个。
在这种情况下,您可以:
key提到的参数:如果您的集合具有多个 2d 和/或多个 2dsphere 索引,则必须使用 key 选项指定要使用的索引字段路径。指定要使用的地理空间索引提供了一个完整示例。
文档中也提到了该错误:
如果有多个 2d 索引或多个 2dsphere 索引并且您没有指定键,MongoDB 将返回错误。
您可以使用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]}}
])
Run Code Online (Sandbox Code Playgroud)
然后我创建两个2dsphere索引:
> db.test.createIndex({loc1:'2dsphere'})
> db.test.createIndex({loc2:'2dsphere'})
Run Code Online (Sandbox Code Playgroud)
$geoNear不指定运行key会输出错误:
> 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",
...
Run Code Online (Sandbox Code Playgroud)
Usingkey: 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 }
Run Code Online (Sandbox Code Playgroud)
并且, usingkey: 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 }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1786 次 |
| 最近记录: |