

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Easiest way to sort an array in MongoDB
The easiest way to sort an array in MongoDB, use $sort. Let us create a collection with documents −
> db.demo242.insertOne( ... ... {"details2": ... [ ... {"ShipingDate":new ISODate("2019-10-11"),"Price":1400}, ... {"ShipingDate":new ISODate("2019-10-01"),"Price":1600 } ... ] ... } ... ...); { "acknowledged" : true, "insertedId" : ObjectId("5e4429229af932883c61ea44") }
Display all documents from a collection with the help of find() method −
> db.demo242.find();
This will produce the following output −
{ "_id" : ObjectId("5e4429229af932883c61ea44"), "details2" : [ { "ShipingDate" : ISODate("2019-10-11T00:00:00Z"), "Price" : 1400 }, { "ShipingDate" : ISODate("2019-10-01T00:00:00Z"), "Price" : 1600 } ] }
Following is the query to sort an array in MongoDB −
> db.demo242.aggregate([ {$unwind: "$details2"}, {$sort: {"details2.ShipingDate":1}}, {$group: {_id:"$_id", details2: {$push:"$details2.ShipingDate"}}} ]);
This will produce the following output −
{ "_id" : ObjectId("5e4429229af932883c61ea44"), "details2" : [ ISODate("2019-10-01T00:00:00Z"), ISODate("2019-10-11T00:00:00Z") ] }
- Related Questions & Answers
- The easiest way to insert date records in MySQL?
- The easiest way to concatenate two arrays in PHP?
- What is the easiest way to lose weight without exercise?
- What is the easiest way to store date in MySQL database?
- What is the easiest way to reverse a String in Java?
- Easiest way to get number of rows in a MySQL table?
- MongoDB query to sort nested array?
- How to sort inner array in MongoDB?
- What is the easiest way to convert int to string in C++
- Best way to sum array size fields in MongoDB?
- What is the easiest way to transfer files from phone to PC?
- Sort MongoDB Collection by Array value?
- Easiest way to copy values of one column to a new table in MySQL?
- What is the easiest way to convert a List to a Set in Java?
- Sort an Array in C++
Advertisements