MongoDB sort() method

MongoDB sort() method

Sorting Documents using sort() method

Using sort() method, you can sort the documents in ascending or descending order based on a particular field of document.

Syntax of sort() method:

db.collecttion_name.find().sort({field_key:1 or -1})

1 is for ascending order and -1 is for descending order. The default value is 1.

For example: collection department data contains following documents:

db.department.find()
{ "_id" : ObjectId("5b3bcdb46728a1b55ecec860"), "dept_id" : 4, "name" : "Sales" }
{ "_id" : ObjectId("5b3725145eb29c373ddadd52"), "dept_id" : 3, "name" : "Production" }
{ "_id" : ObjectId("5b3bced56728a1b55ecec862"), "dept_id" : 5, "name" : "Pre-Sales" }

I want to display the dept_id of all the documents in descending order:

db.department.find({}, {"dept_id": 1,"name":1, _id:0}).sort({"dept_id": -1})

Output:

    { "dept_id" : 5, "name" : "Pre-Sales" }
    { "dept_id" : 4, "name" : "Sales" }
    { "dept_id" : 3, "name" : "Production" }
                

To display the dept_id field of all the department in ascending order:

db.department.find({}, {"dept_id": 1,"name":1, _id:0}).sort({"dept_id": 1})

Output:

    { "dept_id" : 3, "name" : "Production" }
    { "dept_id" : 4, "name" : "Sales" }
    { "dept_id" : 5, "name" : "Pre-Sales" }
                

Default: The default is ascending order so If I don’t provide any value in the sort() method then it will sort the records in ascending order as shown below:

db.department.find({}, {"dept_id": 1, "name":1, _id:0}).sort({})

Output:

    { "dept_id" : 3, "name" : "Production" }
    { "dept_id" : 4, "name" : "Sales" }
    { "dept_id" : 5, "name" : "Pre-Sales" }
                

You can also sort the documents based on the field that you don’t want to display:

For example, you can sort the documents based on dept_id and display the student_name fields.

db.department.find({}, {"name":1, _id:0}).sort({"dept_id": 1})

Output:

    { "name" : "Production" }
    { "name" : "Sales" }
    { "name" : "Pre-Sales" }
                

Leave a Reply

Your email address will not be published. Required fields are marked *