Wie die Fehlermeldung anzeigt, liegt dies daran, dass Sie mehr als eine 2dsphere haben Indizes, also $geoNear weiß nicht, welches man verwenden soll.
In dieser Situation können Sie entweder:
- Löschen Sie den zweiten Geo-Index, oder
- verwenden Sie die
keyParameter wie in der $geoNear-Dokumentation erwähnt :
Der Fehler wird auch in der Dokumentation erwähnt:
Sie können db.collection.getIndexes() verwenden um alle Indizes aufzulisten, die für die Sammlung definiert sind.
Hier ist ein Beispiel für die Verwendung des key Parameter:
> 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]}}
])
Dann erstelle ich zwei 2dsphere Indizes:
> db.test.createIndex({loc1:'2dsphere'})
> db.test.createIndex({loc2:'2dsphere'})
Ausführen von $geoNear ohne Angabe von key gibt den Fehler aus:
> 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",
...
Mit key: loc1 sortiert das Ergebnis nach loc1 index (_id: 0 kommt vor _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 }
Und mit key: loc2 sortiert das Ergebnis nach loc2 index (_id: 1 kommt vor _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 }