我有一个 MongoDB 集合,其中位置数据存储如下:
{
...
longitude: "-73.985679",
latitude: "40.75003",
...
}
我需要在这些上创建一个 2dsphere 索引。有没有办法将这两个单独的字段组合成一个 GeoJSON 格式的数组?
最佳答案
2dsphere 索引的唯一有效形式是 GeoJSON 对象或遗留坐标对。后一种形式是单个字段上的数组或带有“lat”和“lon”键的子文档。
您最好在文档中转换此信息以供持续使用,并使用 GeoJSON 格式。最好和最安全的方法是使用 Bulk操作 API:
var bulk = db.collection.initializeOrderedBulkOp();
var counter = 0;
db.collection.find().forEach(function(doc) {
bulk.find({ "_id": doc._id }).updateOne({
"$set": {
"location": {
"type": "Point",
"coordinates": [ doc.longitude, doc.latitude ]
}
},
"$unset": { "longitude": 1, "latitude": 1 }
});
counter++;
if ( counter % 1000 == 0 ) {
bulk.execute();
bulk = db.collection.initializeOrderedBulkOp();
}
})
if ( counter % 1000 != 0 )
bulk.execute();
您可以使用 eval()
进行一次循环,这样可以更快地运行循环,但不一定“更安全”。
一旦完成,只需在文档中新的“位置”字段上创建索引即可:
db.collection.ensureIndex({ "location": "2dsphere" })
然后您可以在查询中使用该索引。
但是您需要更改文档中的结构,所以请正确操作。
关于Mongodb:在两个字段的数组上创建索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27752268/