Ильич Ленин
Ильич Ленин

Reputation: 107

How to ensure compound 2dsphere Index?

I've read the docs but It does not work as expected. I have the following document:

{
    "_id" : ObjectId("5396e85c12f43f5d1bafbd13"),
    "author" : ObjectId("5396ca2b0fe95cf96599d881"),
    "location" : {
        "address" : "An address",
        "coordinates" : [ 
            12.52891929999998, 
            16.620259
        ],
        "type" : "Point",
        "postal_code" : "333",
        "country" : "Country",
    },
    "description" : "aDescription"
}

And I have the following index in Mongo:

{
    "location" : "2dsphere"
}

How can I create a compound index? Is the following correct:

db.articles.ensureIndex( { location : "2dsphere", postal_code:1, country:1, address:1 } )

What does postal_code:1 or -1 mean?

Upvotes: 0

Views: 790

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151112

The correct form for your document will be:

db.articles.ensureIndex({ 
   "location" : "2dsphere", 
   "location.postal_code":1, 
   "location.country":1, 
   "location.address":1 
})

Since those fields are part of the "location" sub-document you specify the full path with "dot notation".

The notation of 1 or -1 stands for ascending and descending order respectively.

Note that as a compound index these fields are really only of use to you when used in combination of a Geo-spatial query that uses this index since the "2dsphere" index element is first. I would suggest that "country" would be a little to broad for searching "near" or "within" point co-ordinates. But others can effectively filter results.

Upvotes: 1

Related Questions