Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How can I sort documents in MongoDB 4 and display only a single field?
To sort documents in MongoDB and display only a single field, use the sort() method combined with projection. The sort() method orders documents, while projection controls which fields appear in the result.
Syntax
db.collection.find({}, {fieldName: 1}).sort({fieldName: 1});
Where 1 means ascending order and -1 means descending order.
Sample Data
db.demo611.insertMany([
{"Name": "Chris"},
{"Name": "Adam"},
{"Name": "John"},
{"Name": "Bob"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e987110f6b89257f5584d83"),
ObjectId("5e987115f6b89257f5584d84"),
ObjectId("5e987118f6b89257f5584d85"),
ObjectId("5e98711bf6b89257f5584d86")
]
}
Display all documents from the collection ?
db.demo611.find();
{ "_id": ObjectId("5e987110f6b89257f5584d83"), "Name": "Chris" }
{ "_id": ObjectId("5e987115f6b89257f5584d84"), "Name": "Adam" }
{ "_id": ObjectId("5e987118f6b89257f5584d85"), "Name": "John" }
{ "_id": ObjectId("5e98711bf6b89257f5584d86"), "Name": "Bob" }
Example: Sort and Display Single Field
Sort documents by Name field in ascending order and display only the Name field ?
db.demo611.find({}, {Name: 1, _id: 0}).sort({Name: 1});
{ "Name": "Adam" }
{ "Name": "Bob" }
{ "Name": "Chris" }
{ "Name": "John" }
To include the _id field along with the sorted Name field ?
db.demo611.find({}, {Name: 1}).sort({Name: 1});
{ "_id": ObjectId("5e987115f6b89257f5584d84"), "Name": "Adam" }
{ "_id": ObjectId("5e98711bf6b89257f5584d86"), "Name": "Bob" }
{ "_id": ObjectId("5e987110f6b89257f5584d83"), "Name": "Chris" }
{ "_id": ObjectId("5e987118f6b89257f5584d85"), "Name": "John" }
Key Points
- Use
{fieldName: 1}in projection to include only specific fields - Set
{_id: 0}to exclude the_idfield from results -
sort({fieldName: 1})sorts in ascending order,sort({fieldName: -1})sorts in descending order
Conclusion
Combine find() with projection and sort() to display only specific fields in sorted order. Use {fieldName: 1, _id: 0} projection to show only the desired field without the _id.
Advertisements
