- 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
How to sort, select and query subdocument in MongoDB?
To sort, use $sort in MongoDB. Let us create a collection with documents −
> db.demo236.insertOne({"details":{"Name":"Chris","Age":21}}); { "acknowledged" : true, "insertedId" : ObjectId("5e419015f4cebbeaebec514c") } > db.demo236.insertOne({"details":{"Name":"David","Age":23}}); { "acknowledged" : true, "insertedId" : ObjectId("5e41901cf4cebbeaebec514d") } > db.demo236.insertOne({"details":{"Name":"Bob","Age":24}}); { "acknowledged" : true, "insertedId" : ObjectId("5e419023f4cebbeaebec514e") }
Display all documents from a collection with the help of find() method −
> db.demo236.find();
This will produce the following output −
{ "_id" : ObjectId("5e419015f4cebbeaebec514c"), "details" : { "Name" : "Chris", "Age" : 21 } } { "_id" : ObjectId("5e41901cf4cebbeaebec514d"), "details" : { "Name" : "David", "Age" : 23 } } { "_id" : ObjectId("5e419023f4cebbeaebec514e"), "details" : { "Name" : "Bob", "Age" : 24 } }
Following is the query to sort, select and query subdocument in MongoDB −
> db.demo236.aggregate( ... [ ... { $unwind: "$details" }, ... { $project: { ... Name: '$details.Name', ... Age: '$details.Age' ... ... }}, ... { $sort: {Name: -1}} ...] ...);
This will produce the following output −
{ "_id" : ObjectId("5e41901cf4cebbeaebec514d"), "Name" : "David", "Age" : 23 } { "_id" : ObjectId("5e419015f4cebbeaebec514c"), "Name" : "Chris", "Age" : 21 } { "_id" : ObjectId("5e419023f4cebbeaebec514e"), "Name" : "Bob", "Age" : 24 }
- Related Articles
- How to select a specific subdocument in MongoDB?
- Sort by subdocument in MongoDB
- MongoDB to sort by subdocument match?
- MongoDB query to find and return subdocument with criteria?
- MongoDB query to remove subdocument from document?
- Query MongoDB subdocument to print on one line?
- How to query documents by a condition on the subdocument in MongoDB?
- MongoDB query to select distinct and count?
- How to select specific columns in MongoDB query?
- MongoDB aggregate query to sort
- MongoDB query to sort subdocuments
- How to filter array in subdocument with MongoDB?
- MongoDB query on nth element (variable index) of subdocument array
- MongoDB query to sort by words
- MongoDB query to sort nested array?

Advertisements