Reverse array field in MongoDB?

MongoDBDatabaseBig Data Analytics

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"
   ]
}
raja
Published on 21-May-2019 16:11:17
Advertisements