问题
I have created collection and a object is looks like this.
[_id] => MongoId Object (
[$id] => 53087f483b15eaeb6c3c9869
)
[time_from] => 2014-02-22 00:00:00
[time_to] => 2014-02-22 00:10:00
[checkin] => Array (
[0] => Array (
[time_frame] => 2014-02-22 00:00:56
[user_id] => 1
[loc] => Array (
[type] => Point
[coordinates] => Array (
[0] => 73.43
[1] => 42.22
)
)
)
[1] => Array (
[time_frame] => 2014-02-22 00:00:56
[user_id] => 2
[loc] => Array (
[type] => Point
[coordinates] => Array (
[0] => 73.10
[1] => 42.97
)
)
)
}
I need to create "2dsphere" index for 'loc' field. The checkin field has all the location coordinates stored in array format.
I tried creating index like below.
db.<collection>.ensureIndex( { "checkin.loc" : "2dsphere" } );
and I got this below error message.
"err" : "Can't extract geo keys from object, malformed geometry?:{ type: \"Point\", coordinates: [ \"73.10\", \"40.73\" ] }"
What I am missing? Any help would be appreciated! Thanks in advance.
回答1:
The document you provided looks good to me, I also did a simple test with a short version of your document and it works for me.
"_id" : ObjectId("530cb07c009d8c323b477957"),
"time_from" : ISODate("2014-02-25T15:02:20.714Z"),
"checkin" : [
{
"user_id" : 1,
"loc" : {
"type" : "Point",
"coordinates" : [
73.43,
42.22
]
}
}
]
db.testGeo.ensureIndex( { "checkin.loc" : "2dsphere" } );
So I suggest checking other documents in the collection, some of them might be malformed for the index. Also make sure that your coordinates array elements are not strings. Because this document is not valid for 2dsphere index:
"_id" : ObjectId("530cb07c009d8c323b477957"),
"time_from" : ISODate("2014-02-25T15:02:20.714Z"),
"checkin" : [
{
"user_id" : 1,
"loc" : {
"type" : "Point",
"coordinates" : [
"73.43",
"42.22"
]
}
}
]
Please note the quotation marks for the coordinates elements which makes them to be strings.
ANSWER TO THE COMMENT:
Mongo allows only one geospatial index per collection. So you don't have to specify the whole field path for your runCommand. Collection name is enough. This should work for you if the collection name is checkin_20140222
db.runCommand( { geoNear: 'checkin_20140222', near: {type: "Point", coordinates: [73.43, 42.22]}, spherical: true, maxDistance: 40000})
Hope it helps!
来源:https://stackoverflow.com/questions/21980755/mongodb-2dsphere-index-for-nested-array-field