Open In App

Mongoose Query prototype.sort() API

Last Updated : 02 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Mongoose is an Object Data Modeling (ODM) library for MongoDB. It defines a strongly-typed schema, with default values and schema validations which are later mapped to a MongoDB document. 

The Mongoose Query API sort() method is used to sort out the documents, from a collection, using the MongoDB query system. It can be implemented in various ways, like passing a string, an object, or a 2D array of Strings or objects. Let’s understand more about this with some examples.

Syntax:

Query.prototype.sort()

 

Parameters:

  • args: It is of type Object | String | 2D Array of String | Number

Return type: This method returns a Query object.

Creating node application And Installing Mongoose:

Step 1: Create a node application using the following command:

mkdir folder_name
cd folder_name
npm init -y
touch main.js

Step 2: After completing the Node.js application, Install the required module using the following command:

npm install mongoose

Project Structure: It will look like the following.

 

GUI Representation of the  Database using MongoDB Compass: Currently, the collection has no data.

 

Example 1: In this example, we will use the Query API sort() method to sort out the documents based on the name property.

Filename: main.js

Javascript




const mongoose = require('mongoose')
  
// Database connection
mongoose.connect(
    {
        dbName: 'event_db',
        useNewUrlParser: true,
        useUnifiedTopology: true
    }, err => err ? console.log(err)
        : console.log('Connected to database'));
  
const personSchema = new mongoose.Schema({
    name: {
        type: String,
    },
    age: {
        type: Number,
    }
});
  
const personsArray = [
    {
        name: 'Luffy',
        age: 22
    },
    {
        name: 'Nami',
        age: 30
    },
    {
        name: 'Zoro',
        age: 15
    }
]
  
const Person = mongoose.model('Person', personSchema);
  
(async () => {
    await Person.insertMany(personsArray);
  
    const persons = await Person.find().
        sort({ name: 'desc' })
  
    console.log(persons);
})()


Step to Run Application: Run the application using the following command from the root directory of the project:

node main.js

Output: We see that the value remains unchanged in the result.

 

GUI Representation of the  Database using MongoDB Compass:

 

Example 2: In this example, we will use the Query API sort() method to sort out the documents based on the age property.

Filename: main.js

Javascript




const mongoose = require('mongoose')
  
// Database connection
mongoose.connect(
    {
        dbName: 'event_db',
        useNewUrlParser: true,
        useUnifiedTopology: true
    }, err => err ? console.log(err)
        : console.log('Connected to database'));
  
const personSchema = new mongoose.Schema({
    name: {
        type: String,
    },
    age: {
        type: Number,
    }
});
  
const personsArray = [
    {
        name: 'Luffy',
        age: 22
    },
    {
        name: 'Nami',
        age: 30
    },
    {
        name: 'Zoro',
        age: 15
    }
]
  
const Person = mongoose.model('Person', personSchema);
  
(async () => {
    await Person.insertMany(personsArray);
  
    const persons = await Person.find().
        sort('age')
  
    console.log(persons);
})()


Step to Run Application: Run the application using the following command from the root directory of the project:

node main.js

Output: We see that the value remains unchanged in the result.

 

GUI Representation of the  Database using MongoDB Compass:

 

Reference: https://mongoosejs.com/docs/api/query.html#query_Query-sort



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads