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