- 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
Working with MongoDB $sort for sub array document
For sub array document in MongoDB, use aggregate along with $sort. Let us first create a collection with documents −
> db.demo23.insertOne( ...{ ... ... "StudentDetails" : [{ ... "Name" : "David", ... "Age" : 23, ... ... }, { ... "Name" : "Adam", ... "Age" : 24, ... }] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e14c3eb22d07d3b95082e71") }
Display all documents from a collection with the help of find() method −
> db.demo23.find().pretty()
This will produce the following output −
{ "_id" : ObjectId("5e14c3eb22d07d3b95082e71"), "StudentDetails" : [ { "Name" : "David", "Age" : 23 }, { "Name" : "Adam", "Age" : 24 } ] }
Here is the query to work with $sort for sub array document −
> db.demo23.aggregate([ ... { "$unwind" : "$StudentDetails"} , ... { "$sort" : { "StudentDetails.Name" : 1}}, ... { "$match" : { }} , ... { "$group" : { "StudentDetails" : { "$push" : { "Name" : "$StudentDetails.Name"}} , "_id" : null}} , ... { "$project" : { "_id" : 0 , "StudentDetails" : 1}} ... ]);
This will produce the following output −
{ "StudentDetails" : [ { "Name" : "Adam" }, { "Name" : "David" } ] }
- Related Articles
- How to add a sub-document to sub-document array in MongoDB?
- Find the MongoDB document from sub array?
- Filter sub documents by sub document in MongoDB?
- Calculating average value per document with sort in MongoDB?
- MongoDB query for capped sub-collection in an array
- Fetch a specific document in MongoDB with array elements
- Filter query on array of embedded document with MongoDB?
- Pull an element in sub of sub-array in MongoDB?
- How to sum every field in a sub document of MongoDB?
- How to get distinct list of sub-document field values in MongoDB?
- How to add an extra field in a sub document in MongoDB?
- Working with MongoDB find()
- Find document with array that contains a specific value in MongoDB
- MongoDB syntax for updating an object inside an array within a document?
- Sort php multidimensional array by sub-value in PHP

Advertisements