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

MongoDB Aggregate - Lấy phần tử thứ 2 từ dữ liệu đầu vào

Để tổng hợp (aggregate) lấy phần tử thứ 2 từ dữ liệu đầu vào, sử dụng mapReduce(). Map-reduce là mô hình xử lý dữ liệu để凝聚大量数据成有用的聚合结果。

Tạo collection dữ liệu

> db.demo621.insert({ _id: 101, Name1: "John", Name2: "John" });
> db.demo621.insert({ _id: 102, Name1: "Bob", Name2: "John" });
> db.demo621.insert({ _id: 103, Name1: "Chris", Name2: "John" });
> db.demo621.insert({ _id: 104, Name1: "Sam", Name2: "John" });

Hiển thị tất cả

> db.demo621.find();

Kết quả:

{
  "_id" : 101, "Name1" : "John", "Name2" : "John"
}
{
  "_id" : 102, "Name1" : "Bob", "Name2" : "John"
}
{
  "_id" : 103, "Name1" : "Chris", "Name2" : "John"
}
{
  "_id" : 104, "Name1" : "Sam", "Name2" : "John"
}

MapReduce lấy phần tử chẵn (thứ 2, thứ 4...)

> db.demo621.mapReduce(
  function () {
    track++;
    var actualId = this._id;
    delete this._id;
    if (track % div == 0)
      emit(actualId, this);
  },
  function() {},
  {
    "scope": { "track": 0, "div": 2 },
    "out": { "inline": 1 }
  }
)

Kết quả (chỉ _id 102 và 104 - vị trí chẵn):

{
  "results" : [
    { "_id" : 102, "value" : { "Name1" : "Bob", "Name2" : "John" } },
    { "_id" : 104, "value" : { "Name1" : "Sam", "Name2" : "John" } }
  ],
  "timeMillis" : 48,
  "counts" : { "input" : 4, "emit" : 2, "reduce" : 0, "output" : 2 },
  "ok" : 1
}

Giải thích:

  • Biến track đếm thứ tự document (bắt đầu từ 0)
  • div: 2 nghĩa là lấy mỗi 2 document một lần (vị trí chẵn)
  • track % div == 0 phát ra document khi track chia hết cho 2
  • Cách này phù hợp lấy mẫu (sampling) hoặc xử lý theo batch