4

I have a collection with a location field that was entered in the wrong order:

location: [38.7633698, -121.2697997]

When I try to place a 2d index on the field using ...

db.collection.ensureIndex({'location': '2d'});

... I get the following error because the latitude and longitude are reversed.

"err" : "location object expected, location array not in correct format",
"code" : 13654

How can I reverse this array for each document in the mongo shell?

styvane
  • 59,869
  • 19
  • 150
  • 156
matthoiland
  • 912
  • 11
  • 24

3 Answers3

7
db.loc.find().forEach(function (doc) {
    var loc = [ doc.location[1], doc.location[0] ]; 
    db.loc.update(doc, { $set: { location: loc } });
})
Ivan.Srb
  • 1,851
  • 1
  • 14
  • 10
3

Starting from MongoDB 3.4 we can use the $reverseArray operator to do this beautifully.

Reverse the array:

db.collection.aggregate(
    [ 
        { "$project": { "location": { "$reverseArray": "$location" } } }
    ]
)

which yields:

{
    "_id" : ObjectId("576fdc687d33ed2f37a6d527"), 
    "location" : [ -121.2697997, 38.7633698 ] 
}

Update all documents

To update all the documents in your collection, you have a couple of options.

The first is to add a $out stage to your pipeline and replace the old collection. In this case, you will need to explicitly include all the other field in the $projection stage. The $out stage look like this:

{ "$out": "collection" }
styvane
  • 59,869
  • 19
  • 150
  • 156
0

Use $push

to reserve the array using the $each & $sort functionality of it

 db.getCollection('locations').updateMany({},
      { 
        $push: { 
                 'geo_point.coordinates': { $each: [ ], $sort: -1 }
               }
      });
tk120404
  • 2,985
  • 1
  • 27
  • 28