MongoDB文档内查询与文档内两点距离计算方法咨询
嘿,针对你提出的两个MongoDB问题,结合你手里的纽约出租车行程数据集,我来给你详细拆解一下实用的解决方案:
其实你说的“文档内部查询”,就是针对嵌套字段、数组字段这类非顶层字段的查询操作,结合你的数据结构,我给你分几种常见场景举例:
查询基础嵌套字段
你的文档里有geometry_pk和properties两个嵌套层级,用**点符号(.)**指定字段路径就能直接查询:- 筛选所有乘客数为1的行程:
db.trips.find({ "properties.passenger_count": 1 }) - 找出
geometry_pk类型为Point的文档:db.trips.find({ "geometry_pk.type": "Point" })
- 筛选所有乘客数为1的行程:
匹配嵌套数组内的元素
如果你的文档里有数组类型的内部字段(比如行程途经点数组),可以用$elemMatch匹配数组中符合条件的元素。比如要找包含经度在-74到-73之间的途经点的文档:db.trips.find({ "waypoints.coordinates": { $elemMatch: { $gt: -74, $lt: -73 } } })复杂的内部字段比较
要是需要对同一文档内的多个内部字段做逻辑比较,用$expr操作符就能实现。比如假设properties里有上下车时间字段,要找行程时长超过30分钟的记录:db.trips.find({ $expr: { $gt: [ { $subtract: [ "$properties.dropoff_datetime", "$properties.pickup_datetime" ] }, 30 * 60 * 1000 // 转换为毫秒单位 ] } })
纽约出租车数据里一般包含上下车点的坐标,我分两种常见字段结构给你方案:
情况1:字段是GeoJSON Point类型
如果你的properties里有pickup_point和dropoff_point这类Point类型字段(和geometry_pk结构一致),用MongoDB的$distanceSphere能精准计算球面距离(单位为米,符合实际地理距离):- 用聚合查询返回每个行程的ID和距离:
db.trips.aggregate([ { $project: { trip_id: "$properties.ID_Postgres", distance_meters: { $distanceSphere: [ "$properties.pickup_point.coordinates", "$properties.dropoff_point.coordinates" ] } } } ]) - 筛选距离超过1000米的行程:
db.trips.find({ $expr: { $gt: [ { $distanceSphere: [ "$properties.pickup_point.coordinates", "$properties.dropoff_point.coordinates" ] }, 1000 ] } })
- 用聚合查询返回每个行程的ID和距离:
情况2:字段是单独的经纬度数值
如果你的properties里是分开的pickup_longitude、pickup_latitude等字段,把它们组合成坐标数组再用$distanceSphere即可,还能转换成英里单位:db.trips.aggregate([ { $project: { trip_id: "$properties.ID_Postgres", distance_miles: { $divide: [ { $distanceSphere: [ [ "$properties.pickup_longitude", "$properties.pickup_latitude" ], [ "$properties.dropoff_longitude", "$properties.dropoff_latitude" ] ] }, 1609.34 // 1英里≈1609.34米 ] } } } ])
内容的提问来源于stack exchange,提问作者CAGLAYAN ASKIN

