Get the App
SLTechnology News&Howtos  ›  Database  › 

Data query of MongoDB (data sorting)

Shulou Source: shulou.com Published: 2022-06-01 06:45:34 09月21日 Update

In MongoDB, the data sorting operation uses the "sort ()" function, which can be sorted in two orders: ascending (1) and descending (- 1).

Example: data sorting

> db.emp.find () .sort ({"sal":-1}) .pretty ()

{

"_ id": ObjectId ("599108433268c8e84253be2d")

"name": "bastards"

"sex": "male"

"age": 35

"sal": 8000

"loc": "Beijing"

}

But in the process of sorting, there is a way called natural sorting, sorted in the order in which the data is saved, using "$natural".

Example: natural sorting

> db.emp.find () .sort ({"natural":-1}) .pretty ()

{

"_ id": ObjectId ("599108423268c8e84253be26")

"name": "Zhao Yi"

"sex": "male"

"age": 30

"sal": 1000

"loc": "Beijing"

}

{

"_ id": ObjectId ("599108423268c8e84253be27")

"name": "Qian er"

"sex": "female"

"age": 22

"sal": 5000

"loc": "Shanghai"

}

Sorting operations in MongoDB databases are easier to set up than traditional relational databases.

Tags: Sorting data database nature paradigm order Beijing two tradition sequence function ascending order way time is in son of a bitch process Shanghai data query query Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB Redmi Linux Xiaomi vpn