Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Reverse array field in MongoDB?
To reverse array field in MongoDB, you can use the forEach() method to iterate through documents and manually reorder array elements using the $set operator.
Syntax
db.collection.find().forEach(function (document) {
var reversedArray = document.arrayField.reverse();
db.collection.update(document, { $set: {arrayField: reversedArray } });
});
Sample Data
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 the collection ?
db.reverseArrayDemo.find().pretty();
{
"_id" : ObjectId("5ccddf99dceb9a92e6aa1946"),
"Skills" : [
"C",
"Java"
]
}
Method 1: Using forEach() with Manual Index Reversal
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 } });
});
Verify Result
Let us display the document from the collection to check if the array field is now reversed ?
db.reverseArrayDemo.find().pretty();
{
"_id" : ObjectId("5ccddf99dceb9a92e6aa1946"),
"Skills" : [
"Java",
"C"
]
}
Method 2: Using JavaScript reverse() Function
For arrays with dynamic length, use the JavaScript reverse() method ?
db.reverseArrayDemo.find().forEach(function (doc) {
var reversedSkills = doc.Skills.reverse();
db.reverseArrayDemo.update({_id: doc._id}, { $set: {Skills: reversedSkills } });
});
Key Points
-
forEach()iterates through each document in the collection. - Manual indexing works for fixed-size arrays, while
reverse()handles dynamic arrays. - Use
$setoperator to update the array field with reversed values.
Conclusion
MongoDB doesn't have a built-in reverse operator, so use forEach() with JavaScript array methods or manual indexing to reverse array fields. The reverse() method is recommended for dynamic-length arrays.
Advertisements
