Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
  • MongoDB - Get Started
  • What is MongoDB?
  • Install MongoDB
  • MongoDB Server
  • MongoDB Shell
  • MongoDB Shell Commands
  • MongoDB Compass
  • MongoDB Database
  • MongoDB Collections
  • MongoDB Documents
  • Insert Single Document
  • Insert Multiple Documents
  • Import Data into Collection
  • Find Single Document
  • Find Multiple Documents
  • MongoDB Cursor
  • MongoDB Sort Documents
  • Update Single Document
  • Update Multiple Documents
  • Update Arrays
  • Update Embedded Documents
  • Delete Documents
  • Relations in MongoDB
  • Aggregation in MongoDB
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge

Sort Documents in MongoDB Collection

MongoDB provides the db.collection.find() method returns a cursor object for the resulted documents. Use the cursor.sort() method or db.collection.find().sort() to sort the resulted documents in a cursor based on the specified order.

Syntax:

db.collection.find().sort(document)

Parameters:

  1. document: A document that defines the sort order in {field: 1, field:-1,...} format where 1 is for ascending order and -1 is for descending order.

The following inserts documents in the employees collection.

Sample Data
db.employees.insertMany([
    { 
        _id:1,
        firstName: "John",
        lastName: "King",
        email: "[email protected]",
        salary: 5000,
        skills: [ "Angular", "React", "MongoDB" ],
        department: { 
                    "name":"IT" 
                }
    },
    { 
        _id:2,
        firstName: "Sachin",
        lastName: "T",
        email: "[email protected]",
        salary: 8000,
        skills: [ "Accounting", "Tax" ],
        department: { 
                    "name":"Finance" 
                }
    },
    { 
        _id:3,
        firstName: "James",
        lastName: "Bond",
        email: "[email protected]",
        salary: 7500,
        skills: [ "Sales", "Marketing" ],
        department: { 
                    "name":"Marketing" 
                }
    },
    { 
        _id:4,
        firstName: "Steve",
        lastName: "J",
        email: "[email protected]",
        salary: 7000

    },
    { 
        _id:5,
        firstName: "Kapil",
        lastName: "D",
        email: "[email protected]",
        salary: 4500,
        skills: [ "Accounting", "Tax" ],
        department: { 
                    "name":"Finance" 
                }

    },
    { 
        _id:6,
        firstName: "Amitabh",
        lastName: "B",
        email: "[email protected]",
        salary: 7000
    }
])

The following example sorts the employees collection in the ascending order of the firstName field.

Example: sort()
db.employees.find().sort({ firstName:1 })
Output
[
  {
    _id: 6,
    firstName: 'Amitabh',
    lastName: 'B',
    email: '[email protected]',
    salary: 7000
  },
  {
    _id: 3,
    firstName: 'James',
    lastName: 'Bond',
    email: '[email protected]',
    salary: 7500,
    skills: [ 'Sales', 'Marketing' ],
    department: { name: 'Marketing' }
  },
  {
    _id: 1,
    firstName: 'John',
    lastName: 'King',
    email: '[email protected]',
    salary: 5000,
    skills: [ 'Angular', 'React', 'MongoDB' ],
    department: { name: 'IT' }
  },
  {
    _id: 5,
    firstName: 'Kapil',
    lastName: 'D',
    email: '[email protected]',
    salary: 4500,
    skills: [ 'Accounting', 'Tax' ],
    department: { name: 'Finance' }
  },
  {
    _id: 2,
    firstName: 'Sachin',
    lastName: 'T',
    email: '[email protected]',
    salary: 8000,
    skills: [ 'Accounting', 'Tax' ],
    department: { name: 'Finance' }
  },
  {
    _id: 4,
    firstName: 'Steve',
    lastName: 'J',
    email: '[email protected]',
    salary: 7000
  }
]

You can use the cursor object to sort the result. The following returns the same result as above.

Example: cursor.sort()
var cursor = db.employees.find()
cursor.sort({ firstName:1 })

The following example list the sorting on different fields.

Example: sort()
db.employees.find().sort({ _id: -1 })// sorts by descending order of _id
db.employees.find().sort({ salary: -1 })// sorts by descending order of salary
db.employees.find({salary: {$gt:5000}}).sort({ salary: -1 })// find where salary > 5000 and sorts the result by descending order of salary
db.employees.find().sort({ firstName:1, salary: -1 })// sorts by ascending order of firstName and descending order of salary
db.employees.find().sort({"department.name":1}) // sorts by embedded doc department.name

MongoDB uses the following comparison order, from lowest to highest for comparing values of different BSON types.

  1. MinKey (internal type)
  2. Null
  3. Numbers (ints, longs, doubles, decimals)
  4. Symbol, String
  5. Object
  6. Array
  7. BinData
  8. ObjectId
  9. Boolean
  10. Date
  11. Timestamp
  12. Regular Expression
  13. MaxKey (internal type)

Visit BSON type comparison order for more information.

TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.