- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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" ] }
- Related Articles
- MongoDB query for documents matching array, irrespective of elements order
- MongoDB query to filter by several array elements?
- MongoDB query to remove array elements from a document?
- MongoDB query to get array of nested string?
- MongoDB query to fetch array values
- MongoDB query to aggregate nested array
- MongoDB query to sort nested array?
- Query array of subdocuments in MongoDB
- C# Program to order array elements
- C# Program to order array elements in descending order
- MongoDB query to filter object where all elements from nested array match the condition
- MongoDB query to change simple field into an object?
- MongoDB query to get only a specific number of elements
- MongoDB query to slice only one element of array
- MongoDB query to remove item from array?

Advertisements