Bài 16: MongoDB - Sắp xếp bản ghi - MongoDB

Đăng bởi: Admin | Lượt xem: 1237 | Chuyên mục: SQL


Sorting trong MongoDB

Mặc định kết quả truy vấn của method find() trả về sẽ sắp xếp theo field _id
Để tùy chỉnh cách sắp xếp kết quả truy vấn ta dùng method sort() ở sau method find()
Cú pháp:
  • >db.COLLECTION_NAME.find().sort({field1:1, field2:-1,...})
Trong đó:
  • field1:1 tức là sắp xếp tăng dần theo field1
  • field2:-1 tức là sắp xếp giảm dần theo field2
Ví dụ trong collection player mình có những document sau:
{'_id':'1', 'name':'neymar', 'country':'brazil', 'age':25},
{'_id':'2', 'name':'hazard', 'country':'belgium', 'age':25},
{'_id':'3', 'name':'mbappe', 'country':'france', 'age':18},
{'_id':'4', 'name':'modric', 'country':'croatia', 'age':30},
{'_id':'5', 'name':'ronaldo', 'country':'portugal', 'age':33},
{'_id':'6', 'name':'messi', 'country':'argentina', 'age':31},
{'_id':'7', 'name':'icardi', 'country':'argentina', 'age':25},
{'_id':'8', 'name':'griezmann', 'country':'france', 'age':28}
Bây giờ mình muốn sắp xếp theo thứ tự name tăng dần (theo chiều a-z)
db.player.find().sort({'name':1})
Kết quả:
Sắp xếp theo thứ tự country (a-z) + sắp xếp theo age giảm dần:
db.player.find().sort({'country':1, 'age':-1})
Bài tiếp theo: Mongodb - Index >>
vncoder logo

Theo dõi VnCoder trên Facebook, để cập nhật những bài viết, tin tức và khoá học mới nhất!