为mongoDB集合中的所有文档添加2dsphere索引

时间:2015-03-30 00:10:55

标签: arrays mongodb

我有一个mongoDB表,其中long / lat为字段。我需要根据这些字段的值向集合中添加一个2dsphere索引。更新集合中所有文档的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

有这样的文件吗?

> db.test.findOne()
{ "_id" : 0, "lat" : 45.2, "lon" : 37.5 }

在mongo shell中,尝试使用此更新

> db.test.find().forEach(function(doc) {
    var geo = { "type" : "Point", "coordinates" : [doc.lon, doc.lat] }
    db.test.update({ "_id" : doc._id }, { "$set" : { "loc" : geo }, "$unset" : { "lat" : true, "lon" : true } })
})

现在创建地理索引:

> db.test.ensureIndex({ "loc" : "2dsphere" })