
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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" ] }
Advertisements