EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials MongoDB Tutorial order by in MongoDB
Secondary Sidebar
MongoDB Tutorial
  • Commands
    • Mongodb updateMany
    • MongoDB Aggregation
    • Mongodb unwind
    • Mongodb where
    • MongoDB BSON
    • MongoDB Filter
    • Mongodb Match
    • MongoDB sort by date
    • MongoDB Limit()
    • MongoDB Atlas Login
    • MongoDB Relational Database
    • MongoDB count
    • MongoDB Aggregate
    • MongoDB Distinct
    • MongoDB Unique
    • MongoDB find
    • MongoDB findOne()
    • MongoDB insert
    • MongoDB Delete
    • MongoDB Update
    • Lookup in MongoDB
    • order by in MongoDB
    • MongoDB $regex
    • MongoDB $elemMatch
    • MongoDB ObjectId()
    • MongoDB Skip()
    • MongoDB findAndModify
    • Mongodb findOneAndUpdate
    • MongoDB Date Query
    • MongoDB Timestamp
    • MongoDB sort()
    • MongoDB group by
    • MongoDB Join
  • Basics
    • What is MongoDB
    • How To Install MongoDB
    • MongoDB Tools
    • MongoDB GUI Tools
    • MongoDB Versions
    • MongoDB Commands
    • Advantages of MongoDB
    • MongoDB Features
    • Is MongoDB NoSQL
    • Is MongoDB Open Source
    • Build Web Applications using MongoDB
    • MongoDB Data Types
    • MongoDB Administration
    • Data Modeling in MongoDB
    • MongoDB vs Elasticsearch
    • MariaDB vs MongoDB
    • Firebase vs MongoDB
  • Advanced
    • MongoDB Array
    • PostgreSQL ARRAY_AGG()
    • Indexes in MongoDB
    • MongoDB create Index
    • MongoDB Collection
    • MongoDB List Collections
    • MongoDB Capped Collections
    • MongoDB Delete Collection
    • Mongodb show collections
    • MongoDB Auto Increment
    • MongoDB Triggers
    • MongoDB Projection
    • Replication in MongoDB
    • MongoDB Database
    • Mongo DB Create Database
    • MongoDB Compass
    • MongoDB Users
    • MongoDB Authentication
    • MongoDB GridFS
    • MongoDB Relationships
    • MongoDB MapReduce
    • MongoDB Geospatial
    • MongoDB Monitoring
    • Backup in MongoDB
    • MongoDB Sharding
    • MongoDB Java Drivers
    • MongoDB Import
    • Mongo Database Interview Questions
    • MongoDB Join Two Collections
    • MongoDB Group by Multiple Fields
    • MongoDB Pagination
    • MongoDB Replica Set
    • MongoDB Bulk Update
    • MongoDB greater than
    • MongoDB Encryption
    • MongoDB find in array
    • MongoDB like query
    • Mongodb shell
    • MongoDB port
    • MongoDB Query Operators
    • MongoDB Web Interface
    • MongoDB Query Array
    • MongoDB Transactions
    • MongoDB Not In
    • MongoDB not null
    • MongoDB npm
    • MongoDB Remove

Related Courses

MongoDB Certification Course

Oracle Certification Course

All in One Data Science Course

SQL Training Course

Oracle DBA Course

MS SQL Certification Course

order by in MongoDB

By Priya PedamkarPriya Pedamkar

order by in MongoDB

Introduction to order by in MongoDB

By operator sorts the result of the query in an ascending and descending order, ascending and descending order is based on the value we mentioned in the query that is 1 is for ascending order and -1 is for descending order. Order by the command is deprecated in MongoDB shell. MongoDB shell provides cursor.sort() method to query the database.

Syntax:

db.collection.find().sort({field:value})

The “db” stands for database, and the collection stands for collection name we have created under database, find is to find out value from the collection and sort is to be sorting the field, the value from the collection. Sort function requires to complete sorting within 32 megabytes.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (86,584 ratings)

How order by Works in MongoDB?

Order by return value from the collection in ascending or descending order. When we mention field: value pair, it will return value from a given field with chosen descending or ascending order. But we use sort () method, to display value by order wise. We will see a sorting example in the below context.

Examples to Implement order by in MongoDB

Below are the examples of implementing order by in MongoDB:

Example #1

We have created the company database.

Code:

use company

Example #2

We have created a collection under a database company.

Code:

collection_name.insert({field;value})

Example #3

We have inserted a document into a collection.

Code:

db.employee.insert({emp_name:'radhika',age:24,dept:'prod',salary:5000})

Output:

order by in MongoDB - 1

nInserted: 1 – record inserted successfully.

Example #4

We will sort the record by salary-wise in ascending order.

Code:

db.employee.find().sort({salary:1})

Salary is a field, and 1 is valued as we want to display data in ascending order.

order by in MongoDB - 2

Explanation to the above output: We can observe in the above image salary is ordered in ascending order as 4000,5000,6000,7000 and 9000.

Example #5

We will sort the salary in descending order with value -1

Code:

employee.find().sort({salary:-1})

Salary is a field, and -1 is valued as we want to display data in descending order.

order by in MongoDB - 3

Explanation to the above output: We can observe in the above image salary is ordered in descending order as 9000,7000,6000,5000 and 4000.

Example #6

We can apply to sort on string field with the same syntax, and we need to use the same command.

Code:

db.employee.find().sort({emp_name:1})

We can observe in the below image, emp_name is displayed in ascending alphabetic order.

order by in MongoDB - 4

Example #7

We can limit the document while sorting it with LIMIT(). We can mention limit value or can keep it empty.

Code:

db.employee.find().sort({field:value}).limit()

Output:

LIMIT()

Example #8

If we don’t mention the value in the limit, all data will be fetched.

Code:
db.employee.find({},{_id:0}).sort({emp_name:1}).limit()

Output:

fetched

Example #9

While sorting if we don’t mention field: value pair, data will be fetched in ascending order because ascending order is the default order.

We will sort the data by AGE because we have to provide value in find().

Code:

db.employee.find({},{_id:0,age:1}).sort({})

Output:

data by age

Example #10

If we don’t provide any value in find(), default data will be fetched.

Code:

db.employee.find().sort({})

We can observe in the below image, and data is fetched order by with _id.

Output:

order by in MongoDB -8

Example #11

If we mentioned -1 value in find(), and 1 value in sort(), data will be fetched as per sorting value given.

Code:

db.employee.find({},{dept:1,_id:0}).sort({dept:-1})

Dept is sorted in ascending order.

Output:

value in find()

Conclusion

We have studied or learned what is the order by in mongo shell and due to deprecation in the mongo shell cursor.sort() method, we are using to sort the collection. This will help users to get the data as per their choice of ascending or descending order. We can limit the collection using the limit() method.

Recommended Articles

This is a guide to order by MongoDB. Here we discuss Syntax how order by in MongoDB works? And different examples with proper codes and outputs. You can also go through our other related articles to learn more –

  1. Mongo DB Create Database
  2. How To Install MongoDB
  3. MongoDB Alternatives
  4. Is MongoDB Open Source
  5. PostgreSQL ORDER BY | How to Work?
  6. Guide to MongoDB Limit()
Popular Course in this category
MongoDB Training Program (4 Courses, 2 Projects)
  4 Online Courses |  2 Hands-on Projects |  22+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

Oracle Training (14 Courses, 8+ Projects)4.9
All in One Data Science Bundle (360+ Courses, 50+ projects)4.8
SQL Training Program (7 Courses, 8+ Projects)4.7
Oracle DBA Database Management System Training (2 Courses)4.7
MS SQL Training (16 Courses, 11+ Projects)4.7
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more