Question

I have a huge mongodb collection with 6 million records. I have two fields (latitude, longitude), and I would like to add a third field to the collection with the type of point (spatial). How to do this in command line or PHP?

Was it helpful?

Solution

It you'd like to add a new field (with the same value) to all documents in a collection, that can be done easily with an update() operation. Consider the following shell example:

db.collection.update(
  {},
  { $set: { type: "spatial" }},
  { multi: true }
);

This would set the type field to "spatial" for all documents matching empty criteria {} (i.e. everything), and the multi option allows the update to modify multiple documents instead of just the first document matched (default behavior).

If you only wanted to set the type field where it doesn't already exist, you could tweak the criteria like so:

db.collection.update(
  { type: { $exists: false }},
  { $set: { type: "spatial" }},
  { multi: true }
);

Since you're storing geospatial data, you may want to have a look at MongoDB's 2dsphere indexes. This would allow you to store and index well-formed GeoJSON objects in your document. See this previous answer from a related question for more introductory information on the subject.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top