Learn Python

Learn Data Structure & Algorithm

Learn Numpy

Learn Pandas

Learn Matplotlib

Learn Seaborn

Learn Statistics

Learn Math

Learn MATLAB

Learn Machine learning

Learn Github

Learn OpenCV

Learn Deep Learning

Learn MySQL

MongoDB Introduction

MongoDB Setup

MongoDB DataBase

MongoDB Insert Data

MongoDB Read Document

MongoDB Update

MongoDB Delete

MongoDB Sorting Index

MongoDB Aggregation

MongoDB Mongodb with python

Learn Web scraping

Learn Excel

Learn Power BI

Learn Tableau

Learn Docker

Learn Hadoop

Perform sorting in mongodb

Sorting

To perform sorting sort function is used. Inside the sort function, you have to pass the key name and sorting type(ascending or descending) as a dictionary.

.sort({column name:-1 or 1})

For ascending order write 1 and for descending order write -1. The whole collection will sort according to the given column name.You can use a string data type key or number data type key.

Example:
Suppose there is a collection and there is a key named salary. For the salary key, you want to sort the whole table.
So

db.users.find().sort({salary: 1})

For ascending order write 1 and for descending order write -1.

Create index

By creating the index, MongoDB can search inside the collection more faster. To create index ensureIndex() function is used. In the inside the function, you have to pass the key name and the order as a dictionary.

Syntax: .ensureIndex({column name:-1 or 1})

If you want to use multiple key as index then,
Syntax: .ensureIndex({column name:-1 or 1,column name:-1 or 1})

Example:
Suppose you have a key name email. Now you want to make this key as the index.

.ensureIndex({email: 1})

Example:
Suppose you have two keys name email and id. Now you want to make these keys as the index.

.ensureIndex({email:-1,id:1})

CodersAim is created for learning and training a self learner to become a professional from beginner. While using CodersAim, you agree to have read and accepted our terms of use, privacy policy, Contact Us

© Copyright All rights reserved www.CodersAim.com. Developed by CodersAim.