My goal is to fetch documents from a collection based on distance. I attempted to utilize the $geoNear
aggregation, but encountered errors (while using node.js and Postman) or received zero records as output.
Example Document:
{
"_id" : ObjectId("5cc37692fe9fd54b3cd136c9"),
"category" : "art",
"description" : "an eastbound description for The soda event.",
"geometry" : {
"type" : "Point",
"coordinates" : [
3.60178480057443,
6.46123057784917
]
}
"__v" : 0
}
.
.
Data Model:
const GeoSchema = new Schema({
type: {
type: String,
default: "Point"
},
coordinates: {
type: [Number],
index: "2dsphere"
}
}, { _id: false });
const EventSchema = new Schema({
category: String,
description: String,
geometry: GeoSchema,
});
Query Example
db.events.aggregate([
{
$geoNear: {
near: { type: "Point", coordinates: [3.60178480057443, 6.46123057784917] },
distanceField: "dist",
maxDistance: 90000,
spherical: true
}
}
]);
After running the query above, an empty array (on Postman) or no results are returned, occasionally showing this error message:
{
"name": "MongoError",
"errmsg": "exception: geoNear command failed: { ok: 0.0, errmsg: \"more than one 2d index, not sure which to run geoNear on\" }",
"code": 16604,
"ok": 0
}
If the error occurs, I execute the db.events.dropIndex
function. When I followed the examples from the documentation exactly, it worked smoothly. Can anyone provide guidance on how to get the $geoNear function functioning correctly? I've been grappling with it all day.