How to Perform the MongoDB Sort by Field Operation

Introduction

MongoDB is a versatile and scaleable document database that excels in the querying and indexing of data. This tutorial will explain how to use the MongoDB sort by field method. The tutoral will explain the cursor.sort() method that can be used to sort a value by field and can be specified to sort in either ascending or descending order.

Prerequisites

  • MongoDB must be properly installed and working. Execute the mongod –version command in the terminal to confirm the currently installed version of MongoDB.

Start the MongoDB

Execute the following command to start the MongoDB service on a Linux machine:

sudo service mongod start

For a MacOS, execute the following brew command to start MongoDB on a Homebrew installation of MongoDB:

brew services start mongodb

Initialize mongo shell

Mongo shell is an instance terminal and is used for the queries of all commands used in the MongoDB.

Execute the following command to start the Mongo shell:

mongo

Create database in mongo shell

Execute the following command to create a database for holding the value of the data and sorting the data fields using the cursor.sort() method:

> use product
switched to db product

Insert some data

Execute the following commands to use the insert() method and save the document data in MongoDB with the _id field:

> db.product.insert({ "_id" : 1, "item" : { "name" : "HighLander", "type" : "toyota" }, "price" : 1.5 })
WriteResult({ "nInserted" : 1 })
> db.product.insert({ "_id" : 2, "item" : { "name" : "Swift", "type" : "suzuki" }, "price" : 2.9 })
WriteResult({ "nInserted" : 1 })
> db.product.insert({ "_id" : 3, "item" : { "name" : "Mirage G4", "type" : "mitsubishi" }, "price" : 1.2 })
WriteResult({ "nInserted" : 1 })
> db.product.insert({ "_id" : 4, "item" : { "name" : "Altima", "type" : "Nissan" }, "price" : 1.4 })
WriteResult({ "nInserted" : 1 })
> db.product.insert({ "_id" : 5, "item" : { "name" : "Veloster", "type" : "Hyundai" }, "price" : 2.5 })
WriteResult({ "nInserted" : 1 })
> db.product.insert({ "_id" : 6, "item" : { "name" : "Cadenza", "type" : "Kia Motors" }, "price" : 2.1 })
WriteResult({ "nInserted" : 1 })
> db.product.insert({ "_id" : 7, "item" : { "name" : "Corolla", "type" : "Toyota" }, "price" : 1.7})
WriteResult({ "nInserted" : 1 }

Now execute the following command to display the returned document inserted in the MongoDB database:

db.product.find();

NOTE: The display does not automatically sort the data or document(s) when the above command is entered, but just returns the data by _id field in ascending order.

MongoDB sort method

MongoDB’s db.product.find() method can be used to create a cursor object, however, it will have to pass a JSON argument to the .sort() method instead. This will allow it to return a cursor object of MongoDB documents that have been sorted in a particular order.

Sorting MongoDB documents by field names

The following example will produce a result of MongoDB documents sorted by their respective IDs in ascending order:

db.product.find().sort( {"_id" : 1} )

The above command should produce the following results:

{ "_id" : 1, "item" : { "name" : "HighLander", "type" : "toyota" }, "price" : 1.5 }
{ "_id" : 2, "item" : { "name" : "Swift", "type" : "suzuki" }, "price" : 2.9 }
{ "_id" : 3, "item" : { "name" : "Mirage G4", "type" : "mitsubishi" }, "price" : 1.2 }
{ "_id" : 4, "item" : { "name" : "Altima", "type" : "Nissan" }, "price" : 1.4 }
{ "_id" : 5, "item" : { "name" : "Veloster", "type" : "Hyundai" }, "price" : 2.5 }
{ "_id" : 6, "item" : { "name" : "Cadenza", "type" : "Kia Motors" }, "price" : 2.1 }
{ "_id" : 7, "item" : { "name" : "Corolla", "type" : "Toyota" }, "price" : 1.7 }

Screenshot of MongoDB sort by field sorting documents by ID

MongoDB sort cursor

A cursor is essentially a JavaScript object that stores MongoDB documents according to a certain pattern. The following command utilizes a simple cursor count() method that returns the total number of documents in a MongoDB collection:

var countCursor = db.product.count();

In this example, the above Mongo shell command should return lucky number 7, as shown in the second line from the bottom of the following image:

Screenshot of MongoDB sort by field example getting count cursor in mongo Shell

Now perform the cursor.sort() method in descending order of the field price given by the document data.

For this example, input the following command into the Mongo shell prompt that passes a JSON object to the db.product.find().sort() method:

db.product.find().sort( { price: -1 } )

The results should resemble the following:

{ "_id" : 2, "item" : { "name" : "Swift", "type" : "suzuki" }, "price" : 2.9 }
{ "_id" : 5, "item" : { "name" : "Veloster", "type" : "Hyundai" }, "price" : 2.5 }
{ "_id" : 6, "item" : { "name" : "Cadenza", "type" : "Kia Motors" }, "price" : 2.1 }
{ "_id" : 7, "item" : { "name" : "Corolla", "type" : "Toyota" }, "price" : 1.7 }
{ "_id" : 1, "item" : { "name" : "HighLander", "type" : "toyota" }, "price" : 1.5 }
{ "_id" : 4, "item" : { "name" : "Altima", "type" : "Nissan" }, "price" : 1.4 }
{ "_id" : 3, "item" : { "name" : "Mirage G4", "type" : "mitsubishi" }, "price" : 1.2 }

NOTE: The -1 JSON parameter is used for sorting documents in descending order. For ascending order, use 1 instead.

Note how the prices of each MongoDB document are now sorted in a descending order. To assign the above sorting cursor to a variable, use the following JavaScript command to declare a new variable with var:

var priceCursor = db.product.find().sort( { price: -1 } )

Now type the priceCursor variable name into the mongo Shell prompt to print the below image of the above cursor variable:

Screenshot of MongoDB sort by field cursor object

Type quit() to exit the Mongo shell when finished.

Conclusion

This tutorial explained how to use the MongoDB sort by field method to sort a value by field and can be specified to sort in either ascending or descending order. The tutorial also covered how to start the MongoDB on both a Linux machine and a MacOS, how to initialize the Mongo shell, how to create a database and insert data into the Mongo shell. The article also explained how to execute the MongoDB sort method and sort documents by field names. Remember to use the -1 JSON parameter for sorting in descending order and 1 for sorting in ascending order when executing the MongoDB sort by field method.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.