Using aggregation we can consolidate the geospatial field creation into a single command. It is important to note that the current values for latitude and longitude are stored as a data type string, and hence are unusable for the purposes of geospatial queries. Accordingly, we employ the $toDouble pipeline expression operator.
Here is the command that adds a new field, geo_spatial_flat, consisting of legacy coordinate pairs, from existing latitude and longitude coordinates in the world_cities collection:
db.world_cities.aggregate(
{ "$match": {} },
{ "$addFields": {
"geo_spatial_flat" : [
{ "$toDouble" : "$longitude" },
{ "$toDouble" : "$latitude" } ]
}
},
{ "$out" : "world_cities" }
);
This command uses three stages: $match, $addFields, and $out:
- The $match stage has an empty filter...