Reverse array field in MongoDB?


To reverse array field in MongoDB, you can use forEach(). Let us first create a collection with documents −

> db.reverseArrayDemo.insertOne({"Skills":["C","Java"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ccddf99dceb9a92e6aa1946")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.reverseArrayDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5ccddf99dceb9a92e6aa1946"),
   "Skills" : [
      "C",
      "Java"
   ]
}

Here is the query to reverse array field in MongoDB −

> db.reverseArrayDemo.find().forEach(function (myDocument) {
...    var arrayValue = [ myDocument.Skills[1], myDocument.Skills[0] ];
...    db.reverseArrayDemo.update(myDocument, { $set: {Skills : arrayValue } });
... });

Let us display the document from the above collection to check the array field is now reversed or not −

> db.reverseArrayDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5ccddf99dceb9a92e6aa1946"),
   "Skills" : [
      "Java",
      "C"
   ]
}

Updated on: 30-Jul-2019

175 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements