Reverse array field in MongoDB

懵懂的女人 提交于 2019-12-20 01:09:21

问题


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?


回答1:


db.loc.find().forEach(function (doc) {
    var loc = [ doc.location[1], doc.location[0] ]; 
    db.loc.update(doc, { $set: { location: loc } });
})



回答2:


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" }


来源:https://stackoverflow.com/questions/22053975/reverse-array-field-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!