Reverse array field in MongoDB

后端 未结 2 1067
一整个雨季
一整个雨季 2021-01-19 10:44

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 2

2条回答
  •  南笙
    南笙 (楼主)
    2021-01-19 11:04

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

提交回复
热议问题