MongoDB query to change order of array elements?


Use swap concept to change the order of array elements. Let us create a collection with documents −

> db.demo301.insertOne({"Name":["Chris","David","Bob"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4d6ff55d93261e4bc9ea51")
}

Display all documents from a collection with the help of find() method −

> db.demo301.find();

This will produce the following output −

{ "_id" : ObjectId("5e4d6ff55d93261e4bc9ea51"), "Name" : [ "Chris", "David", "Bob" ] }

Following is the query to change the order of array elements −

> db.demo301.find({}, { Name : 1 }).forEach(function(n) {
...   var t = n.Name[0];
...   n.Name[0] = n.Name[1];
...   n.Name[1] = t;
...   db.demo301.update({ _id: n._id }, { $set: { Name: n.Name } });
...})

Display all documents from a collection with the help of find() method −

> db.demo301.find();

This will produce the following output −

{ "_id" : ObjectId("5e4d6ff55d93261e4bc9ea51"), "Name" : [ "David", "Chris", "Bob" ] }

Updated on: 01-Apr-2020

454 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements