- 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
Sort id and reverse the items with MongoDB
The $natural returns the documents in natural order. To reverse the items, use $natural:-1. Let us create a collection with documents −
> db.demo710.insertOne({id:101,Name:"Robert"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea83a855d33e20ed1097b7a") } > db.demo710.insertOne({id:102,Name:"Carol"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea83a8d5d33e20ed1097b7b") } > db.demo710.insertOne({id:103,Name:"Mike"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea83a935d33e20ed1097b7c") } > db.demo710.insertOne({id:104,Name:"Sam"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea83a9b5d33e20ed1097b7d") }
Display all documents from a collection with the help of find() method −
> db.demo710.find();
This will produce the following output −
{ "_id" : ObjectId("5ea83a855d33e20ed1097b7a"), "id" : 101, "Name" : "Robert" } { "_id" : ObjectId("5ea83a8d5d33e20ed1097b7b"), "id" : 102, "Name" : "Carol" } { "_id" : ObjectId("5ea83a935d33e20ed1097b7c"), "id" : 103, "Name" : "Mike" } { "_id" : ObjectId("5ea83a9b5d33e20ed1097b7d"), "id" : 104, "Name" : "Sam" }
Following is the query to sort and reverse the items −
> db.demo710.find().sort({$natural:-1});
This will produce the following output −
{ "_id" : ObjectId("5ea83a9b5d33e20ed1097b7d"), "id" : 104, "Name" : "Sam" } { "_id" : ObjectId("5ea83a935d33e20ed1097b7c"), "id" : 103, "Name" : "Mike" } { "_id" : ObjectId("5ea83a8d5d33e20ed1097b7b"), "id" : 102, "Name" : "Carol" } { "_id" : ObjectId("5ea83a855d33e20ed1097b7a"), "id" : 101, "Name" : "Robert" }
- Related Articles
- Matching MongoDB collection items by id?
- Wrap the flex items in reverse order with CSS
- Sort items in MySQL with dots?
- Update a MongoDB document with Student Id and Name
- Implement $dateToString on array items with MongoDB
- Sort items of an ArrayList with Collections.reverseOrder() in Java
- How to get element with max id in MongoDB?
- How to count items in array with MongoDB?
- Grouping the array items in MongoDB and get the count the products with similar price?
- Sort the MongoDB documents in ascending order with aggregation?
- Match ID and fetch documents with $eq in MongoDB in case of array?
- Python program to sort and reverse a given list
- Filtering MongoDB items by fields and subfields?
- How do I get email-id from a MongoDB document and display with print()
- Hide id field in MongoDB

Advertisements