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

Duyệt qua tất cả collection MongoDB và thực thi truy vấn

Để lặp qua tất cả các collection trong database, dùng getCollectionNames() kết hợp forEach().

Ví dụ: Lấy timestamp của tài liệu mới nhất (theo _id giảm dần, limit 1) từ mỗi collection trong database test:

> db.getCollectionNames().forEach(function(collectionName) {
    var latestDoc = db[collectionName].find().sort({_id: -1}).limit(1);
    if (latestDoc.hasNext()) {
        printjson(latestDoc.next()._id.getTimestamp());
    }
});

Kết quả mẫu:

ISODate("2019-02-21T18:52:43Z")
ISODate("2019-03-19T17:49:00Z")
ISODate("2019-03-06T15:40:12Z")
ISODate("2019-03-15T16:31:50Z")
... (các timestamp khác)

Giải thích:

  • db.getCollectionNames(): Trả về mảng tên tất cả collection.
  • forEach(): Lặp qua từng tên collection.
  • db[collectionName]: Truy cập collection động theo tên.
  • sort({_id: -1}).limit(1): Lấy tài liệu có _id lớn nhất (mới nhất).
  • _id.getTimestamp(): Trích xuất thời gian tạo từ ObjectId.

Lưu ý: Cách này chỉ hoạt động nếu _id là ObjectId (mặc định). Nếu _id tự định nghĩa, getTimestamp() sẽ báo lỗi.