0
votes

I'm using CosmosDB with MongoDb API and I'd like to use $nearSphere to find Documents.

Here is the exemple of one document I have in my collection "locations":

{
    "_id": {
        "$oid": "60523b3dd72e4d4aa21f473b"
    },
    "data": [{
        "Indicateur": "pr50mm",
        "Value": 0,
        "score": 0,
        "Exposure": "low"
    }],
    "Domain": "EU-CORDEX",
    "GCMS": "ICHEC-EC-EARTH",
    "RCMS": "RACMO22E",
    "Scenario": "rcp85",
    "Horizon": "Medium (1941-1970)",
    "location": {
        "type": "Point",
        "coordinates": [26.32, 27.25]
    }
}

I would like to find the Document with location the nearest from [26, 27]. When I execute the following request, it returns nothing. However, this same command works fine we a MongoDB database : It returns the documents order by distance with point with coordonates [26, 27].

db.locations.find({
  'location': {
    $nearSphere: {
      $geometry: {
        type: 'Point',
        coordinates: [
          26, 27
        ]
      }
    }
  }
})

Do you know how I can make it work for Azure CosmosDB?

Thank you in advance.

1
I tried in my place and I found that if I execute the query with the variable [26.32, 27.25], it can return documents, but when I used [26, 27], it returns nothing, could you pls check if coordonates [26, 27] exists in your mongodb database?tiny-wa
@Tiny-wa I have the same result than you. No, I don't have any document with [26,27]. However, I don't expect it returns only document with exact location match, but the nearest location from [26, 27] (Which is, in my case : [26.32, 27.25]). Thank for you help.ThBM
Thanks for your response, and if you are urgen to figure out this feature, I think you can try this. {$nearSphere: {$geometry: {type : "Point",coordinates : [26.32, 27.25]}, $minDistance: <distance in meters>, $maxDistance: <distance in meters> }} Using $minDistance and $maxDistance then can got nearest location. But it still needs to use the exact coordinates as the parameter here.tiny-wa
By the way, have you added the 2dsphere index for the db? Document said that using $nearSphere needs that index, though when my executing the query without the index it didn't return error.tiny-wa
@Tiny-wa, thank you for your help, I found the solution: I had to specify location.coordinates in my query. Also, you cannot add 2dsphere index on Azure CosmosDBThBM

1 Answers

0
votes

It looks like for Azure CosmosDB I have to specify location.coordinates in my query. Here is the working query:

db.locations.find({
  'location.coordinates': {
    $nearSphere: {
      $geometry: {
        type: 'Point',
        coordinates: [
          26, 27
        ]
      }
    }
  }
})

This exemple about $nearSphere helped me: https://github.com/MicrosoftDocs/azure-docs/blob/master/articles/cosmos-db/mongodb-feature-support.md

I hope this will help other people!