Blog

Sắp xếp bản ghi trong MongoDB

Last updated on November 1st, 2022 at 05:26 pm

Phương thức sort() trong MongoDB

Để sắp xếp các Document trong MongoDB, bạn cần sử dụng phương thức sort(). Phương thức sort() nhận một Document chứa danh sách các trường cùng với thứ tự sắp xếp của chúng. Để xác định thứ tự sắp xếp, 1 và -1 được sử dụng. 1 được sử dụng cho thứ tự tăng dần, trong khi -1 được sử dụng cho thứ tự giảm dần.

Cú pháp

Cú pháp cơ bản của phương thức sort() là như sau:

>db.COLLECTION_NAME.find().sort({KEY:1})

Ví dụ

Bạn theo dõi Collection với tên mycol có dữ liệu sau:

{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}

Ví dụ sau hiển thị Document được sắp xếp bởi title theo thứ tự giảm dần.

>db.mycol.find({},{"title":1,_id:0}).sort({"title":-1})
{"title":"Tutorials Point Overview"}
{"title":"NoSQL Overview"}
{"title":"MongoDB Overview"}
>

Ghi nhớ nếu bạn không xác định thứ tự sắp xếp, thì phương thức sort() sẽ hiển thị Document theo thứ tự tăng dần.

Nguồn: Internet

Chúng tôi chuyên cung cấp những khóa học về Phân tích dữ liệu, đăng ký ngay để nhận được tư vấn chi tiết lộ trình dành riêng cho bạn nhé!

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    bujangjp slotsensa slot88 slot4d slot4d slot4d sv388 slot88 suhubet demo slot slot4d demo slot https://fabritec.pe/asesor.php suhubet bujangjp https://kibf.pk/ slotsensa buku303 slot4d sbobet slot gacor slot gacor slot gacor totogacor slot thailand slot thailand slot gacor slot luar negeri slot gacor 4d totogacor slot gacor wd jutaan slotsensa slot gacor slot gacor slotsensa slot gacor slot dana slot dana https://cliffcrestinn.com/ totogacor totogacor demo slot slot 4d totogacor totogacor demo slot totogacor slot thailand totogacor bujangjp situs gacor 4D situs gacor Situs Gacor 4D Thailand Situs Gacor 4D SLOT4D bujangjp