如何使用 Python 更新 MongoDB 中的地理位置字段

在 MongoDB 中更新地理位置字段需要使用 Geospatial operators。具体来说,需要使用 $set 和 $geometry 操作符。

以下是一个示例代码,用于更新名为 “test” 的集合中所有文档的地理位置字段 “location”:

from pymongo import MongoClient, GEOSPHERE

# 连接 MongoDB
client = MongoClient()
db = client['test']
collection = db['test']

# 创建 Geospatial 索引
collection.create_index([("location", GEOSPHERE)])

# 更新地理位置
updated_documents = collection.update_many({}, {"$set": {"location": {"type": "Point", "coordinates": [-122.4194, 37.7749]}}})

# 输出更新数量
print(updated_documents.modified_count)

这个示例代码中,我们首先连接到数据库和集合。然后,我们使用 create_index 函数创建 Geospatial 索引,这可以显著加速地理位置查询。接下来,我们使用 update_many 函数更新所有文档的 location 字段。我们使用 $set 操作符设置字段的新值。值本身是一个包含 type 和 coordinates 两个键的字典,类型是 “Point”,坐标是 [-122.4194, 37.7749],表示旧金山的经度和纬度。最后,我们输出更新的文档数量。

如果您要更新的是字符串类型的地理位置字段,需要在更新之前将其转换为 Geospatial 对象。以下代码根据“pidancode.com”字符串更新文档:

from pymongo import MongoClient, GEOSPHERE, Point

# 连接 MongoDB
client = MongoClient()
db = client['test']
collection = db['test']

# 创建 Geospatial 索引
collection.create_index([("location", GEOSPHERE)])

# 更新地理位置
location = Point(-122.4194, 37.7749)
updated_documents = collection.update_many({"url": "pidancode.com"}, {"$set": {"location": location}})

# 输出更新数量
print(updated_documents.modified_count)

在这里,我们创建了一个新的 Point 对象,并将其用作更新操作中的新值。我们还使用 url 字段作为查询条件,仅更新 url 为 “pidancode.com”的文档。

相关文章