Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swap the values in a MongoDB array

I have an array like "geo": [39.897867,-121.8909978] in my MongoDb collection.

What I need to do is to swap the values present inside the array.

Please help me on this. Thank you...

like image 266
Prakki Avatar asked Oct 27 '25 19:10

Prakki


1 Answers

You can swap by using array index . First find it and swap it.

db.myCollection.find().forEach(function(doc){
        db.myCollection.update({_id: doc._id},
          {$set: {"geo.0": doc.geo[1], "geo.1": doc.geo[0]}})
    })
like image 90
Sumeet Kumar Yadav Avatar answered Oct 30 '25 17:10

Sumeet Kumar Yadav



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!