MongoDB query to change order of array elements?

To change the order of array elements in MongoDB, you can use JavaScript operations with the forEach() method to swap elements or use aggregation pipeline with array operators for more complex reordering.

Syntax

// Method 1: Using forEach with JavaScript swap
db.collection.find().forEach(function(doc) {
    // Swap elements using temporary variable
    var temp = doc.arrayField[index1];
    doc.arrayField[index1] = doc.arrayField[index2];
    doc.arrayField[index2] = temp;
    db.collection.update({_id: doc._id}, {$set: {arrayField: doc.arrayField}});
});

// Method 2: Using $set with explicit array
db.collection.update(
    {_id: ObjectId("id")},
    {$set: {arrayField: ["newOrder1", "newOrder2", "newOrder3"]}}
);

Sample Data

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

Method 1: Using forEach with Element Swap

Swap the first two elements (Chris and David) using JavaScript ?

db.demo301.find({}, { Name: 1 }).forEach(function(doc) {
    var temp = doc.Name[0];
    doc.Name[0] = doc.Name[1];
    doc.Name[1] = temp;
    db.demo301.update({ _id: doc._id }, { $set: { Name: doc.Name } });
});
db.demo301.find();
{ "_id": ObjectId("5e4d6ff55d93261e4bc9ea51"), "Name": ["David", "Chris", "Bob"] }

Method 2: Using $set with Explicit Reordering

Completely reorder the array to ["Bob", "David", "Chris"] ?

db.demo301.update(
    { _id: ObjectId("5e4d6ff55d93261e4bc9ea51") },
    { $set: { Name: ["Bob", "David", "Chris"] } }
);
{ "_id": ObjectId("5e4d6ff55d93261e4bc9ea51"), "Name": ["Bob", "David", "Chris"] }

Key Points

  • forEach method allows JavaScript-based swapping for dynamic operations
  • $set operator directly replaces the entire array with new ordering
  • Use forEach for conditional swaps, $set for explicit reordering

Conclusion

MongoDB supports array reordering through JavaScript forEach operations for swapping elements or $set operator for explicit array replacement. Choose forEach for dynamic swaps and $set for predetermined order changes.

Updated on: 2026-03-15T02:20:51+05:30

641 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements