Data query of MongoDB (data sorting)
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.