Zoals de foutmelding aangeeft, komt dit omdat u meer dan één 2dsphere . heeft indexen, dus $geoNear weet niet welke te gebruiken.
In deze situatie kunt u ofwel:
- laat de tweede geografische index vallen, of
- gebruik de
keyparameter zoals vermeld in de $geoNear-documentatie :
De fout wordt ook in de documenten vermeld:
U kunt db.collection.getIndexes() gebruiken om alle indexen weer te geven die in de collectie zijn gedefinieerd.
Hier is een voorbeeld van het gebruik van de 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]}}
])
Dan maak ik twee 2dsphere indexen:
> db.test.createIndex({loc1:'2dsphere'})
> db.test.createIndex({loc2:'2dsphere'})
$geoNear uitvoeren zonder key op te geven zal de fout weergeven:
> 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",
...
Met behulp van key: loc1 sorteert het resultaat volgens de loc1 index (_id: 0 komt voor _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 }
En, met behulp van key: loc2 sorteert het resultaat volgens de loc2 index (_id: 1 komt voor _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 }