I'm working with node (using the MongoClient library) and mongodb, trying to add a geospatial index to my data
The records in my collection have a longitude and latitude field. I understand that in order to create a geospatial index, you need a location field that corresponds to the geoJson point format (https://medium.com/@AbbasPlusPlus/geospatial-data-in-mongodb-storage-indexing-and-queries-1c6db21b7970) . Therefore after inserting the data I run:
async function addLocation() {
const res = collection.updateMany(
{ location: { $exists: false } }, // filter
{
$set: {
location: {
type: "Point",
coordinates: ["$longitude", "$latitude"],
},
},
}
);
}
Next, I tried to add a geospatial index with:
async function createIndex() {
try {
await collection.createIndex({ location: "2dsphere" });
console.log('Index created');
} catch (err) {
console.error(err);
}
}
This gives the error in the title
Looking at the records I saw the screenshot. I assume the long, lat fields should have numbers instead of operators.
How can I fix addLocation, so that it puts correct values in the long, lat fields?
to update fields based on values of other fields or if you want to use complex expressions(ex- $map
etc) you'll have to use the bracket notation with updates
see aggregation pipeline with updates
const res = collection.updateMany(
{ location: { $exists: false } },
[
{
$set: {
location: {
type: "Point",
coordinates: ["$longitude", "$latitude"],
},
},
}
]
);