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

Cách liệt kê tất cả collection trong một database MongoDB

Để liệt kê tất cả các collection từ một database cụ thể, bạn cần chuyển sang database đó trước.

Cách 1: Sử dụng getCollectionNames()

> use sample
switched to db sample
> db.getCollectionNames();
[
  "copyThisCollectionToSampleDatabaseDemo",
  "deleteDocuments",
  "deleteDocumentsDemo",
  "deleteInformation",
  "employee",
  "internalArraySizeDemo",
  "sourceCollection",
  "updateInformation",
  "userInformation"
]

Cách 2: Sử dụng lệnh show collections

> show collections;
copyThisCollectionToSampleDatabaseDemo deleteDocuments deleteDocumentsDemo deleteInformation employee internalArraySizeDemo sourceCollection updateInformation userInformation

Cả hai cách đều cho kết quả giống nhau, show collections ngắn gọn hơn trong khi getCollectionNames() trả về mảng có thể xử lý tiếp trong script.