Add a new field point type filed to a collection with value of an existing field

StackOverflow https://stackoverflow.com/questions/21602888

  •  07-10-2022
  •  | 
  •  

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?

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top