1

Currently, I have my lat/long in separate fields in my MongoDB database, but if I want to do geospatial searching I need to have them in this format:

{ location : [ 50 , 30 ] } 

By what means can I transpose the values of my lat/long keys into a new key per document as per above?

TIA!

Amresh
  • 478
  • 1
  • 6
  • 28
occasl
  • 5,303
  • 5
  • 56
  • 81
  • 1
    Read out the old document, flip the values, write the result. Don't lost track of which ones you updated. Am I missing something? – Eric J. Jul 31 '12 at 01:24
  • Yeah, that's right. Just was wondering how. This post seems to cover it: http://stackoverflow.com/questions/3788256/mongodb-updating-documents-using-data-from-the-same-document/3792958#3792958 – occasl Jul 31 '12 at 17:15

1 Answers1

1

You will have to iterate through all your documents that don't have a location field and add it (presumably deleting the lat/long fields unless this will break your application).

db.mycollection.find( { location : { $exists : false } } ).forEach(
    function (doc) {
        // Add (lon, lat) pairs .. order is important
        doc.location = { lon: doc.lon, lat: doc.lat };

        // Remove old properties
        delete doc.lon;
        delete doc.lat;

        // Save the updated document
        db.mycollection.save(doc);
    }
)

Note that the order for MongoDB geospatial indexing should be consistent in your document as (longitude, latitude).

Stennie
  • 63,885
  • 14
  • 149
  • 175
  • Of course it's transposing...what would you call it?? I want to change the shape of the data not the actual values (i.e., transforming). I get how to find the docs, but I'm unsure the mechanism to iterate...is that map reduce function or something? – occasl Jul 31 '12 at 16:37
  • @occasl: you're correct, transposing is an appropriate term .. I inferred something else. Map/reduce copies into a new output collection so if you want to iterate in place a forEach is appropriate. Revised the example to include an update. – Stennie Jul 31 '12 at 21:50
  • Thanks...that's what I ended up doing. – occasl Aug 01 '12 at 17:58