Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse array field in MongoDB

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?

like image 670
matthoiland Avatar asked Dec 26 '22 12:12

matthoiland


1 Answers

db.loc.find().forEach(function (doc) {
    var loc = [ doc.location[1], doc.location[0] ]; 
    db.loc.update(doc, { $set: { location: loc } });
})
like image 198
Ivan.Srb Avatar answered Jan 15 '23 08:01

Ivan.Srb