MongoDB Tutorial
Advanced MongoDB
MongoDB Useful Resources
Selected Reading
- MongoDB - PHP
- MongoDB - Java
- MongoDB - Deployment
- MongoDB - Create Backup
- MongoDB - Sharding
- MongoDB - Replication
- MongoDB - Aggregation
- MongoDB - Indexing
- MongoDB - Sorting Records
- MongoDB - Limiting Records
- MongoDB - Projection
- MongoDB - Delete Document
- MongoDB - Update Document
- MongoDB - Query Document
- MongoDB - Insert Document
- MongoDB - Data Types
- MongoDB - Drop Collection
- MongoDB - Create Collection
- MongoDB - Drop Database
- MongoDB - Create Database
- MongoDB - Data Modeling
- MongoDB - Environment
- MongoDB - Advantages
- MongoDB - Overview
- MongoDB - Home
Advanced MongoDB
- Auto-Increment Sequence
- MongoDB - Capped Collections
- MongoDB - GridFS
- Working with Rockmongo
- MongoDB - Regular Expression
- MongoDB - Text Search
- MongoDB - Map Reduce
- MongoDB - ObjectId
- MongoDB - Indexing Limitations
- MongoDB - Advanced Indexing
- MongoDB - Atomic Operations
- MongoDB - Analyzing Queries
- MongoDB - Covered Queries
- MongoDB - Database References
- MongoDB - Relationships
MongoDB Useful Resources
- MongoDB - Discussion
- MongoDB - Useful Resources
- MongoDB - Quick Guide
- MongoDB - Questions and Answers
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
MongoDB - Sorting Records
MongoDB - Sort Records
In this chapter, we will learn how to sort records in MongoDB.
The sort() Method
To sort documents in MongoDB, you need to use sort() method. The method accepts a document containing a pst of fields along with their sorting order. To specify sorting order 1 and -1 are used. 1 is used for ascending order while -1 is used for descending order.
Syntax
The basic syntax of sort() method is as follows −
>db.COLLECTION_NAME.find().sort({KEY:1})
Example
Consider the collection myycol has the following data.
{_id : ObjectId("507f191e810c19729de860e1"), title: "MongoDB Overview"} {_id : ObjectId("507f191e810c19729de860e2"), title: "NoSQL Overview"} {_id : ObjectId("507f191e810c19729de860e3"), title: "Tutorials Point Overview"}
Following example will display the documents sorted by title in the descending order.
>db.mycol.find({},{"title":1,_id:0}).sort({"title":-1}) {"title":"Tutorials Point Overview"} {"title":"NoSQL Overview"} {"title":"MongoDB Overview"} >
Please note, if you don t specify the sorting preference, then sort() method will display the documents in ascending order.
Advertisements