我正在使用 python 和 mongodb。我有一个包含 40000 个文档的集合。我有一组坐标,我需要找到这些坐标属于哪个文档。现在我正在做:
cell_start = citymap.find({"cell_latlng":{"$geoIntersects":{"$geometry":{"type":"Point", "coordinates":orig_coord}}}})
该方法是典型的geoJSON方法,效果很好。现在我知道有些文档有这样一个字段:
{'trips_dest':......}
这个字段的值并不重要,所以我跳过它。问题是,我不必从所有这 40000 个文档中查找文档,我可以只从具有名为 'trips_dest' 的字段的文档中查找文档。
因为我知道只有大约 40% 的文档有字段 'trips_dest' 所以我认为这会提高效率。但是,我不知道如何修改我的代码来做到这一点。有什么想法吗?
最佳答案
您需要 $exists查询运算符。类似的东西:
cell_start = citymap.find({"trips_dest": {$exists: true},
"cell_latlng":{"$geoIntersects":{"$geometry":{"type":"Point", "coordinates":orig_coord}}}})
引用文档:
Syntax:
{ field: { $exists: <boolean> } }
When
<boolean>
is true,$exists
matches the documents that contain the field, including documents where the field value is null
如果您需要拒绝null 值,请使用:
"trips_dest": {$exists: true, $ne: null}
最后一点,sparse index最终可能会加快此类查询的速度。
关于python:如何查找具有特定字段的文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30155345/