(+84) 236.3827111 ex. 402

Kỹ thuật sắp xếp dữ liệu MongoDB bằng C#


Cụ thể ta sẽ làm các chức năng sau:
  1. Tải toàn bộ dữ liệu trong bảng Product (Try 1)
  2. Tải toàn bộ dữ liệu trong bảng Product và sắp xếp theo đơn giá tăng dần (Try 2)
  3. Tải toàn bộ dữ liệu trong bảng Product và sắp xếp theo đơn giá giảm dần (Try 3)
  4. Lọc Product theo đơn giá [a…b] (Try 4)
  5. Lọc Product theo đơn giá [a…b] và sắp xếp (Try 5)
  6. Tải toàn bộ dữ liệu trong bảng Product và sắp xếp theo đơn giá tăng dần, nếu đơn giá trùng nhau thì sắp xếp theo Mã giảm dần (Try 6)
  7. Thoát
  8. Kết thúc bài học bạn phải làm được chương trình như hình dưới đây:

    Để sắp xếp dữ liệu trong quá trình truy vấn ta dùng đối tượng: Builders.Sort

    Trong đối tượng này có rất nhiều phương thức, ta quan tâm 2 phương thức chính đã là Sắp tăng dần (Ascending) và Sắp giảm dần (Descending).

    Ví dụ: Muốn viết lệnh sắp xếp Product theo Cột Đơn Giá tăng dần:

    var sort = Builders<BsonDocument>.Sort.Ascending(“DonGia”);

    Ví dụ: Muốn viết lệnh sắp xếp Product theo Cột Đơn Giá Giảm dần:
    var sort = Builders<BsonDocument>.Sort.Descending(“DonGia”);

    Tương tự như vậy, nếu bạn muốn sắp xếp cột nào thì thay DonGia bằng Cột bạn muốn sắp xếp.

    Sau đó ta truyền đối tượng sort vào lệnh truy vấn dữ liệu(các lệnh truy vấn bạn đã được học rất kỹ ở những bài 5, 6, 7, 8 rồi):

    List documents = collection.Find(new BsonDocument()).Sort(sort).ToList();

    Ví dụ: Sắp xếp kết hợp nhiều cột:

    var sort = Builders.Sort.Ascending(“DonGia”).Descending(“Ma”);

    Lệnh trên có nghĩa: Sắp xếp theo đơn giá tăng dần, nếu đơn giá trùng nhau thì sắp xếp theo Mã giảm dần.

    OK, let’s go. Bây giờ ta tạo một Project tên : SortMongoDBCSharp, cách tham chiếu thư viện MongoDB driver bạn tự xem lại bài 4. Trong bài này Tui đi thẳng vào thiết kế giao diện và xử lý các hàm truy vấn dữ liệu và sắp xếp ở trên.

    Thiết kế giao diện MainWindow.xaml:

    1

    Xử lý coding cho MainWindow.xaml.cs:

    0. Lớp Product để ta convert qua Model cho lẹ:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    namespace SortMongoDBCSharp
    {
    public class Product
    {
    public object _id { get; set; }
    public string Ma { get; set; }
    public string Ten { get; set; }
    public double DonGia { get; set; }
    }
    }

    Chú ý lớp này Tui cũng đã giải thích ở bài 8

    1.Tải toàn bộ dữ liệu trong bảng Product (Try 1)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    private void btnTry1_Click(object sender, RoutedEventArgs e)
    {
    LoadAll();
    }
    private void LoadAll()
    {
    MongoClient client = new MongoClient("mongodb://localhost:27017");
    IMongoDatabase database = client.GetDatabase("QuanLySanPham");
    IMongoCollection collection = database.GetCollection("Product");
    List documents = collection.Find(new BsonDocument()).ToList();
    List dsProduct = new List();
    foreach (BsonDocument document in documents)
    {
    Product p = BsonSerializer.Deserialize(document);
    dsProduct.Add(p);
    }
    lvProduct.ItemsSource = dsProduct;
    }

    Đoạn lệnh trên ta đã rất quen thuộc, đó là tải toàn bộ sản phẩm lên giao diện.

    Kết quả:

    2.Tải toàn bộ dữ liệu trong bảng Product và sắp xếp theo đơn giá tăng dần (Try 2)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    private void btnTry2_Click(object sender, RoutedEventArgs e)
    {
    LoadAll_Sort_Ascending();
    }
    private void LoadAll_Sort_Ascending()
    {
    MongoClient client = new MongoClient("mongodb://localhost:27017");
    IMongoDatabase database = client.GetDatabase("QuanLySanPham");
    IMongoCollection collection = database.GetCollection("Product");
    var sort = Builders.Sort.Ascending("DonGia");
    List documents = collection.Find(new BsonDocument()).Sort(sort).ToList();
    List dsProduct = new List();
    foreach (BsonDocument document in documents)
    {
    Product p = BsonSerializer.Deserialize(document);
    dsProduct.Add(p);
    }
    lvProduct.ItemsSource = dsProduct;
    }

    Đoạn coding ở trên ta thấy:

    var sort = Builders.Sort.Ascending(“DonGia”);

    dùng để tạo đối tượng Sort tăng dần theo cột đơn giá.

    Còn lệnh dưới đây là gán đối tượng Sort đó vào hàm lấy danh sách. Như vậy sau khi truy vấn nó sẽ sắp xếp dữ liệu theo cột đơn giá:

    List documents = collection.Find(new BsonDocument()).Sort(sort).ToList();

    Kết quả:

    3.Tải toàn bộ dữ liệu trong bảng Product và sắp xếp theo đơn giá giảm dần (Try 3)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    private void btnTry3_Click(object sender, RoutedEventArgs e)
    {
    LoadAll_Sort_Descending();
    }
    private void LoadAll_Sort_Descending()
    {
    MongoClient client = new MongoClient("mongodb://localhost:27017");
    IMongoDatabase database = client.GetDatabase("QuanLySanPham");
    IMongoCollection collection = database.GetCollection("Product");
    var sort = Builders.Sort.Descending("DonGia");
    List documents = collection.Find(new BsonDocument()).Sort(sort).ToList();
    List dsProduct = new List();
    foreach (BsonDocument document in documents)
    {
    Product p = BsonSerializer.Deserialize(document);
    dsProduct.Add(p);
    }
    lvProduct.ItemsSource = dsProduct;
    }

    Đoạn coding ở trên ta thấy:

    var sort = Builders.Sort.Descending(“DonGia”);

    dùng để tạo đối tượng Sort giảm dần theo cột đơn giá.

    Còn lệnh dưới đây là gán đối tượng Sort đó vào hàm lấy danh sách. Như vậy sau khi truy vấn nó sẽ sắp xếp dữ liệu theo cột đơn giá:

    List documents = collection.Find(new BsonDocument()).Sort(sort).ToList();

    Kết quả:

    4.Lọc Product theo đơn giá [a…b] (Try 4)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    private void btnTry4_Click(object sender, RoutedEventArgs e)
    {
    LoadFilterProduct(150, 250);
    }
    private void LoadFilterProduct(double min,double max)
    {
    MongoClient client = new MongoClient("mongodb://localhost:27017");
    IMongoDatabase database = client.GetDatabase("QuanLySanPham");
    IMongoCollection collection = database.GetCollection("Product");
    var filter = Builders.Filter.Gte("DonGia", min) & Builders.Filter.Lte("DonGia", max);
    List documents = collection.Find(filter).ToList();
    List dsProduct = new List();
    foreach (BsonDocument document in documents)
    {
    Product p = BsonSerializer.Deserialize(document);
    dsProduct.Add(p);
    }
    lvProduct.ItemsSource = dsProduct;
    }

    Ở trên Tui viết riêng một hàm LoadFilterProduct(double min,double max) lọc Product theo đơn giá Min và max. các Em chỉ cần gọi hàm và truyền giá trị vào mà thôi nên rất tiện lợi. Cách lọc này Ta cũng đã được học kỹ trong bài 7.

    Kết quả:

    5.Lọc Product theo đơn giá [a…b] và sắp xếp đơn giá giảm dần (Try 5)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    private void btnTry5_Click(object sender, RoutedEventArgs e)
    {
    LoadFilter_Sort_Descending(150, 250);
    }
    private void LoadFilter_Sort_Descending(double min, double max)
    {
    MongoClient client = new MongoClient("mongodb://localhost:27017");
    IMongoDatabase database = client.GetDatabase("QuanLySanPham");
    IMongoCollection collection = database.GetCollection("Product");
    var filter = Builders.Filter.Gte("DonGia", min) & Builders.Filter.Lte("DonGia", max);
    var sort = Builders.Sort.Descending("DonGia");
    List documents = collection.Find(filter).Sort(sort).ToList();
    List dsProduct = new List();
    foreach (BsonDocument document in documents)
    {
    Product p = BsonSerializer.Deserialize(document);
    dsProduct.Add(p);
    }
    lvProduct.ItemsSource = dsProduct;
    }

    Tương tự như try 4, ở đây Tui tạo hàm độc lập LoadFilter_Sort_Descending(double min, double max) và kết hợp thêm Sort giảm dần. Như vậy vừa filter vừa sort giảm dần (bạn có thể áp dụng cho tăng dần).

    Kết quả:

    6.Tải toàn bộ dữ liệu trong bảng Product và sắp xếp theo đơn giá tăng dần, nếu đơn giá trùng nhau thì sắp xếp theo Mã giảm dần (Try 6)

    Đây là một trong nhưng yêu cầu được sử dụng rất nhiều trong phần mềm. Ta làm như sau:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    private void btnTry6_Click(object sender, RoutedEventArgs e)
    {
    LoadAll_Sort_Ascending_Descending();
    }
    private void LoadAll_Sort_Ascending_Descending()
    {
    MongoClient client = new MongoClient("mongodb://localhost:27017");
    IMongoDatabase database = client.GetDatabase("QuanLySanPham");
    IMongoCollection collection = database.GetCollection("Product");
    var sort = Builders.Sort.Ascending("DonGia").Descending("Ma");
    List documents = collection.Find(new BsonDocument()).Sort(sort).ToList();
    List dsProduct = new List();
    foreach (BsonDocument document in documents)
    {
    Product p = BsonSerializer.Deserialize(document);
    dsProduct.Add(p);
    }
    lvProduct.ItemsSource = dsProduct;
    }

    Bạn quan sát:

    var sort = Builders.Sort.Ascending(“DonGia”).Descending(“Ma”);

    Là sự kết hợp của nhiều yêu cầu Sort. Cụ thể: Sắp xếp Đơn giá tăng dần, nếu đơn giá trùng nhau thì sắp xếp theo Mã giảm dần. Bạn có thể áp dụng để làm các yêu cầu tương tự.

    Kết quả:

    Bạn quan sát, Sản phẩm Sting Lavie có đơn giá trùng nhau. Nó sẽ sắp xếp giảm dần về Mã, Tức là Sting có mã P6 sẽ được liệt kê trước sản phẩm Lavie có mã là P4.

    7.Thoát

    Rất đơn giá, chỉ cần gọi lệnh Close();

    1
    2
    3
    4
    private void btnExit_Click(object sender, RoutedEventArgs e)
    {
    Close();
    }

    Dưới đây là tổng hợp XAML và Coding đầy đủ:

    MainWindow.xaml:

    1

    Coding đầy đủ: MainWindow.xaml.cs:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    using MongoDB.Bson;
    using MongoDB.Bson.Serialization;
    using MongoDB.Driver;
    using MongoDB.Driver.Builders;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    namespace SortMongoDBCSharp
    {
    ///
    /// Interaction logic for MainWindow.xaml
    ///
    public partial class MainWindow : Window
    {
    public MainWindow()
    {
    InitializeComponent();
    }
    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
    }
    private void btnExit_Click(object sender, RoutedEventArgs e)
    {
    Close();
    }
    private void btnTry1_Click(object sender, RoutedEventArgs e)
    {
    LoadAll();
    }
    private void LoadAll()
    {
    MongoClient client = new MongoClient("mongodb://localhost:27017");
    IMongoDatabase database = client.GetDatabase("QuanLySanPham");
    IMongoCollection collection = database.GetCollection("Product");
    List documents = collection.Find(new BsonDocument()).ToList();
    List dsProduct = new List();
    foreach (BsonDocument document in documents)
    {
    Product p = BsonSerializer.Deserialize(document);
    dsProduct.Add(p);
    }
    lvProduct.ItemsSource = dsProduct;
    }
    private void btnTry2_Click(object sender, RoutedEventArgs e)
    {
    LoadAll_Sort_Ascending();
    }
    private void LoadAll_Sort_Ascending()
    {
    MongoClient client = new MongoClient("mongodb://localhost:27017");
    IMongoDatabase database = client.GetDatabase("QuanLySanPham");
    IMongoCollection collection = database.GetCollection("Product");
    var sort = Builders.Sort.Ascending("DonGia");
    List documents = collection.Find(new BsonDocument()).Sort(sort).ToList();
    List dsProduct = new List();
    foreach (BsonDocument document in documents)
    {
    Product p = BsonSerializer.Deserialize(document);
    dsProduct.Add(p);
    }
    lvProduct.ItemsSource = dsProduct;
    }
    private void btnTry3_Click(object sender, RoutedEventArgs e)
    {
    LoadAll_Sort_Descending();
    }
    private void LoadAll_Sort_Descending()
    {
    MongoClient client = new MongoClient("mongodb://localhost:27017");
    IMongoDatabase database = client.GetDatabase("QuanLySanPham");
    IMongoCollection collection = database.GetCollection("Product");
    var sort = Builders.Sort.Descending("DonGia");
    List documents = collection.Find(new BsonDocument()).Sort(sort).ToList();
    List dsProduct = new List();
    foreach (BsonDocument document in documents)
    {
    Product p = BsonSerializer.Deserialize(document);
    dsProduct.Add(p);
    }
    lvProduct.ItemsSource = dsProduct;
    }
    private void btnTry4_Click(object sender, RoutedEventArgs e)
    {
    LoadFilterProduct(150, 250);
    }
    private void LoadFilterProduct(double min,double max)
    {
    MongoClient client = new MongoClient("mongodb://localhost:27017");
    IMongoDatabase database = client.GetDatabase("QuanLySanPham");
    IMongoCollection collection = database.GetCollection("Product");
    var filter = Builders.Filter.Gte("DonGia", min) & Builders.Filter.Lte("DonGia", max);
    List documents = collection.Find(filter).ToList();
    List dsProduct = new List();
    foreach (BsonDocument document in documents)
    {
    Product p = BsonSerializer.Deserialize(document);
    dsProduct.Add(p);
    }
    lvProduct.ItemsSource = dsProduct;
    }
    private void btnTry5_Click(object sender, RoutedEventArgs e)
    {
    LoadFilter_Sort_Descending(150, 250);
    }
    private void LoadFilter_Sort_Descending(double min, double max)
    {
    MongoClient client = new MongoClient("mongodb://localhost:27017");
    IMongoDatabase database = client.GetDatabase("QuanLySanPham");
    IMongoCollection collection = database.GetCollection("Product");
    var filter = Builders.Filter.Gte("DonGia", min) & Builders.Filter.Lte("DonGia", max);
    var sort = Builders.Sort.Descending("DonGia");
    List documents = collection.Find(filter).Sort(sort).ToList();
    List dsProduct = new List();
    foreach (BsonDocument document in documents)
    {
    Product p = BsonSerializer.Deserialize(document);
    dsProduct.Add(p);
    }
    lvProduct.ItemsSource = dsProduct;
    }
    private void btnTry6_Click(object sender, RoutedEventArgs e)
    {
    LoadAll_Sort_Ascending_Descending();
    }
    private void LoadAll_Sort_Ascending_Descending()
    {
    MongoClient client = new MongoClient("mongodb://localhost:27017");
    IMongoDatabase database = client.GetDatabase("QuanLySanPham");
    IMongoCollection collection = database.GetCollection("Product");
    var sort = Builders.Sort.Ascending("DonGia").Descending("Ma");
    List documents = collection.Find(new BsonDocument()).Sort(sort).ToList();
    List dsProduct = new List();
    foreach (BsonDocument document in documents)
    {
    Product p = BsonSerializer.Deserialize(document);
    dsProduct.Add(p);
    }
    lvProduct.ItemsSource = dsProduct;
    }
    }
    }

    Chạy chương trình lên ta có được kết quả như mong muốn.