Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Lọc log chứa từ khóa "work" trong MongoDB Aggregation

Dùng $filter trong aggregation để lọc các phần tử mảng thỏa mãn điều kiện (chứa từ "work" không phân biệt hoa thường).

Tạo collection:

> db.demo383.insertOne({
  "ServerName":"Jboss",
  "ServerLogs": [
    {"status":"Working"},
    {"status":"Stop"},
    {"status":"Worked"}
  ]
});
{ "acknowledged" : true, "insertedId" : ObjectId("5e5b635422064be7ab44e7f1") }

Xem dữ liệu:

> db.demo383.find().pretty();

Aggregation lọc log chứa "work":

> db.demo383.aggregate([
  { "$addFields": {
    "ServerLogs": {
      "$filter": {
        "input": "$ServerLogs",
        "cond": {
          "$ne": [
            { "$indexOfBytes": [
              { "$toUpper": "$$this.status" },
              { "$toUpper": "work" }
            ]},
            -1
          ]
        }
      }
    }
  }}
])

Kết quả (chỉ giữ Working, Worked):

Phân tích:

  • $addFields: ghi đè trường ServerLogs bằng kết quả lọc
  • $filter: duyệt mảng, giữ phần tử thoả cond
  • $toUpper: chuyển cả hai về chữ hoa để so sánh case-insensitive
  • $indexOfBytes: tìm vị trí chuỗi con, trả -1 nếu không tìm thấy
  • $ne: [..., -1]: giữ nếu tìm thấy (khác -1)

MongoDB 4.2+: Dùng $regexMatch đơn giản hơn: {$regexMatch: {input: "$$this.status", regex: "work", options: "i"}}.