pymongo使用update_many()插入新属性使用当前属性值

2024-10-03 11:15:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个具有以下属性的文档:

{'_id':1, 
  'longitude':1.1 //double, 
  'latitude':1.2 //double}
}

我想使用pymongo添加2D geo index

我有以下代码:

collection.create_index([('loc', pymongo.GEO2D)])
data = collection.update_many({},
                          {'$set':{'loc':['$latitude','$longitude']}})

但我得到的结果是一个错误 pymongo.errors.OperationFailure: location object expected, location array not in correct format

这是因为我插入了两个字符串和“$latitude”,“$longitude”。如何插入纬度和经度的实际值

非常感谢您的帮助

更新:我知道我可以用for循环完成它。但我想避免这样做,因为这将是非常缓慢的


Tags: 代码文档idindex属性createlocationloc
1条回答
网友
1楼 · 发布于 2024-10-03 11:15:34

$set操作似乎不支持Collection.update上的2D indexes

2D索引是遗留的,可能不会添加对$set的支持

使用聚合修复当前问题,如下所示:

field = {'loc': ['$longitude', '$latitude']}
# write documents with added field as a workaround to $set not supporting
# legacy 2D indexes
collection.aggregate([{'$addFields': field}, {'$out': 'collection-name'}])
<>我强烈建议考虑使用^ a2}索引。 2Dsphere支持所有地理空间查询,从长远来看,这对您的用例可能是有益的

相关问题 更多 >