 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
How can I sort documents in MongoDB 4 and display only a single field?
To sort documents in MongoDB 4, use sort(). To show only a single field, which is sorted, set it to 1.
Let us create a collection with documents −
> db.demo611.insertOne({"Name":"Chris"});{    "acknowledged" : true, "insertedId" : ObjectId("5e987110f6b89257f5584d83") } > db.demo611.insertOne({"Name":"Adam"});{    "acknowledged" : true, "insertedId" : ObjectId("5e987115f6b89257f5584d84") } > db.demo611.insertOne({"Name":"John"});{    "acknowledged" : true, "insertedId" : ObjectId("5e987118f6b89257f5584d85") } > db.demo611.insertOne({"Name":"Bob"});{    "acknowledged" : true, "insertedId" : ObjectId("5e98711bf6b89257f5584d86") } Display all documents from a collection with the help of find() method −
> db.demo611.find(); This will produce the following output: { "_id" : ObjectId("5e987110f6b89257f5584d83"), "Name" : "Chris" } { "_id" : ObjectId("5e987115f6b89257f5584d84"), "Name" : "Adam" } { "_id" : ObjectId("5e987118f6b89257f5584d85"), "Name" : "John" } { "_id" : ObjectId("5e98711bf6b89257f5584d86"), "Name" : "Bob" } Following is the query to sort documents using MongoDB 4 −
> db.demo611.find().sort({Name:1}); This will produce the following output &mius;
{ "_id" : ObjectId("5e987115f6b89257f5584d84"), "Name" : "Adam" } { "_id" : ObjectId("5e98711bf6b89257f5584d86"), "Name" : "Bob" } { "_id" : ObjectId("5e987110f6b89257f5584d83"), "Name" : "Chris" } { "_id" : ObjectId("5e987118f6b89257f5584d85"), "Name" : "John" }Advertisements
 