Jak wskazuje komunikat o błędzie, dzieje się tak, ponieważ masz więcej niż jedną 2dsphere indeksy, więc $geoNear nie wie, którego użyć.
W takiej sytuacji możesz:
- upuść drugi indeks geograficzny lub
- użyj
keyparametr jak wspomniano w dokumentacji $geoNear :
Błąd jest również wymieniony w dokumentacji:
Możesz użyć db.collection.getIndexes() aby wyświetlić wszystkie indeksy zdefiniowane w kolekcji.
Oto przykład użycia key parametr:
> 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]}}
])
Następnie tworzę dwa 2dsphere indeksy:
> db.test.createIndex({loc1:'2dsphere'})
> db.test.createIndex({loc2:'2dsphere'})
Uruchamianie $geoNear bez określania key zwróci błąd:
> 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",
...
Używając key: loc1 posortuje wynik zgodnie z loc1 indeks (_id: 0 występuje przed _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 }
I używając key: loc2 posortuje wynik zgodnie z loc2 indeks (_id: 1 występuje przed _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 }