Sorting data with MongoDB

 

In the recent articles, we’ve seen what MongoDB is and how to install MongoDB on Windows. We’ve also evaluated the best available GUI tools to use along with your MongoDB database instance. With all these details, let’s get started with one of the in-action sessions on how to query / update and also workaround with the data on retrieval. Let us get started with that, no further delay.

If you want to enrich your career and become a professional in MongoDB, then visit Mindmajix - a global online training platform: "MongoDB Training" This course will help you to achieve excellence in this domain. 

Let’s take this in a step-by-step process – there are 5 steps to this process. The first is to create a database of our choice, the second step is to create a collection under the database that we have created. The next step is to create a set of documents under the collection that we have created. The next step is to query on the documents set of the collection and then comes the last leg, sort the documents set as per our wish.

How to Sort Data with MongoDB?

1. Create a database in MongoDB:

The command to use to create a database in MongoDB database is used. The command when used along with a database name, will create the database if it doesn’t exist and if exists returns the database. 

Let’s try creating a database with the name ‘SampleSortExampleDB’.

Mongo DB Data base

A point to note here is that command show dbs will not list your database as existing without at least one record inserted into it. Hence to check whether the database is created or not, you may want to check it with the same command as above – which ensures that the database exists.

MindMajix Youtube Channel

2. Create a collection within our new database:

The command to use to create a collection in the database that we have just created in the step above is as follows:

db.createCollection(name, options)

name is the name of your new Collection that you are going to create.

option is a document to specify the configuration of your collection, which is an optional parameter

1. capped – If mentioned true then it creates a capped collection (a fixed-size collection which overwrites the oldest entries on reaching the size value mentioned)

2. autoIndexId – Default is false, but when marked true it indexes on _idfields.

3. size – mentions the maximum size of a capped collection (mandatory if capped is true)

4. max – mentions the number of documents allowed in a capped collection.

For our example, let us proceed with an ordinary collection, screenshot follows:

Create collection in Mongodb database

3. Insert / Update documents in MongoDB Database:

The commands to use in MongoDB to create a record/document on the database is either update() or save(). If we try to run the insert command without creating the collection, then MongoDB creates the collection first, and then it inserts the document as per the command. If you want to insert more than one document in a single insert query then you can pass all the details in an array separated by commas.

Related Article: Create collection in MongoDB

The basic syntax for inserting a document into a collection is as follows:

db.SampleSortExampleCollection.insert(document)

Let’s take a look at an example of how to insert a document into our MongoDB collection that we have created in the step above. Screenshot follows:

Insert / Update document

For ease of use, provided the syntax for creating a document in the collection along with the screenshot as well:

db.SampleSortExampleCollection.insert([{
_id : ObjectId(1234567890),
documentTiltle : ‘MongoDB Collections Document Insert’,
documentDescription : ‘Very first document Insert into MongoDB NoSQL database’,
documentCreatedBy : ‘SRR’,
documentURL : ‘localhost/Document_1’,
documentTags : [‘MongoDB’, ‘NoSQL’],
documentTopic : ‘MongoDB NoSQL Database’  
}])

Let’s now see how we can update an existing document via the MongoBooster GUI tool. Use GUI tool or not, the commands to achieve will be the same on a MongoDB shell or the GUI tool. Hence this should be just fine to use either the MongoDB shell or the GUI tool.

MongoBooster GUI tool

4. Querying documents:

Now that we are able to insert and update documents via the commands above, let us try to query the MongoDB database and the collection for a specific set of documents out of the existing set of documents. For this, we have created a set of documents in the collection just like as it’s shown above.

There are many methods available for querying the documents on MongoDB database/collection - let’s take two examples on how to use them on two different use cases, screenshots with the syntax follows:

Checkout MongoDB Tutorial

i. find()

Querying documents

find() the method requires what column you want to query your collection about and based on that the matching result set will be displayed for us to choose from. findOne() method again requires the same but here that the query result should be unique, _id will be returned in the projection even if it is not selected as part of the select list or something.

The _id is a 12-byte hexadecimal number that is unique for every document that gets inserted into a collection of a MongoDB database. This is by default the design of MongoDB database.

ii. findOne()

Querying documents findone

5. Sorting documents:

Now with the brief introduction into the basic MongoDB database operations like INSERT, UPDATE, and QUERY – we are now on the last leg on sorting the documents as per the JSON structure that we have defined for our documents in the collection. 

For easier explanation, let me show just the fields on which we will sort – so that the data and the sort() function can be understood better.

{"documentTitle" : "MongoDB Database Creation"},
{"documentTitle" : "MongoDB Database Collection Creation"},
{"documentTitle" : "MongoDB Database Collection Document Inserted"},
{"documentTitle" : "MongoDB Database Collection Document Updated"},
{"documentTitle" : "MongoDB Collections Document Update"},
{"documentTitle" : "KnockOutJS"},
{"documentTitle" : "AngularJS CLI"},
{"documentTitle" : "AngularJS Filters"},
{"documentTitle" : "AngularJS Directives"}

Screenshots with the commands on how to sort (in the descending order based on ‘documentTitle’ field) is as follows:

MongoDB Sorting

Screenshots with the commands on how to sort (in the ascending order based on ‘documentTitle’ field) is as follows:

MongoBooster Sorting

Conclusion:

Using the MongoDB shell is next to easy if you know the commands to use. If you find it difficult to use the MongoDB shell all by yourself, then you can completely rely on any of the GUI tools for your OS type. For Windows, we suggest that you use the MongoBooster GUI tool for all your operations on the MongoDB database.

 

Course Schedule
NameDates
MongoDB Training Oct 15 to Oct 30View Details
MongoDB Training Oct 19 to Nov 03View Details
MongoDB Training Oct 22 to Nov 06View Details
MongoDB Training Oct 26 to Nov 10View Details
Last updated: 03 Apr 2023
About Author

Prasanthi is an expert writer in MongoDB, and has written for various reputable online and print publications. At present, she is working for MindMajix, and writes content not only on MongoDB, but also on Sharepoint, Uipath, and AWS.

read less