When attempting to use dynamic coordinates ($lat
and $lng
) in a MongoDB aggregation pipeline for geospatial queries, I encountered the error message “Point must only contain numeric elements.” This error suggests that the dynamic values are not being recognized as numeric elements within the geospatial query. As a result, the query fails to execute properly. I am seeking a solution to resolve this issue and successfully use dynamic values in geospatial queries in MongoDB.
The working solution"
db.dataofweek9of2023.aggregate([
{
$match: {
"data.featureName": "TripsBoard",
"data.lat": { $ne: null },
"data.lng": { $ne: null }
}
},
{
$limit: 1
},
{
$addFields: {
lat: { $toDouble: "$data.lat" },
lng: { $toDouble: "$data.lng" }
}
},
{
$lookup: {
from: "bangladesh_geojson",
let: {
lat: "$lat",
lng: "$lng"
},
pipeline: [
{
$unwind: "$features"
},
{
$match: {
"features.geometry": {
$geoIntersects: {
$geometry: {
type: "Point",
coordinates: [ 90.416, 23.7935 ]
}
}
}
}
},
{
$project: {
_id: 0,
district: "$features.properties.shapeName"
}
}
],
as: "districts"
}
}
])
The non working solution:
db.dataofweek9of2023.aggregate([
{
$match: {
"data.featureName": "TripsBoard",
"data.lat": { $ne: null },
"data.lng": { $ne: null }
}
},
{
$limit: 1
},
{
$addFields: {
lat: { $toDouble: "$data.lat" },
lng: { $toDouble: "$data.lng" }
}
},
{
$lookup: {
from: "bangladesh_geojson",
let: {
lat: "$lat",
lng: "$lng"
},
pipeline: [
{
$unwind: "$features"
},
{
$match: {
"features.geometry": {
$geoIntersects: {
$geometry: {
type: "Point",
coordinates: [ "$$lat", "$$lng" ]
}
}
}
}
},
{
$project: {
_id: 0,
district: "$features.properties.shapeName"
}
}
],
as: "districts"
}
}
])
Error log:
{
"message" : "Point must only contain numeric elements",
"ok" : 0,
"code" : 2,
"codeName" : "BadValue"
}