Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

วิธีดูรายชื่อฐานข้อมูลและคอลเลกชันทั้งหมดใน MongoDB Server

MongoDB Shell มีคำสั่งสำหรับแสดงรายการฐานข้อมูลและคอลเลกชันทั้งหมดใน Server

1. แสดงรายชื่อฐานข้อมูลทั้งหมด (List All Databases)

use admin
db.runCommand({listDatabases: 1})

ตัวอย่างผลลัพธ์

> use admin
switched to db admin
> db.runCommand({listDatabases: 1});

ผลลัพธ์:

{
  "databases": [
    {"name": "admin", "sizeOnDisk": 1675264, "empty": false},
    {"name": "config", "sizeOnDisk": 131072, "empty": false},
    {"name": "local", "sizeOnDisk": 77824, "empty": false},
    {"name": "main", "sizeOnDisk": 184320, "empty": false},
    {"name": "my", "sizeOnDisk": 753664, "empty": false},
    {"name": "sample", "sizeOnDisk": 1286144, "empty": false},
    {"name": "sampleDemo", "sizeOnDisk": 352256, "empty": false},
    {"name": "studentSearch", "sizeOnDisk": 262144, "empty": false},
    {"name": "test", "sizeOnDisk": 15810560, "empty": false},
    {"name": "university", "sizeOnDisk": 229376, "empty": false},
    {"name": "web", "sizeOnDisk": 217088, "empty": false}
  ],
  "totalSize": 20979712,
  "ok": 1
}

2. แสดงรายชื่อคอลเลกชันในฐานข้อมูลเฉพาะ (List Collections in a Database)

use yourDatabaseName
db.getCollectionNames()

ตัวอย่าง: ดูคอลเลกชันในฐานข้อมูล "sample"

> use sample
switched to db sample
> db.getCollectionNames();

ผลลัพธ์:

[
  "arraySizeErrorDemo", "atleastOneMatchDemo", "basicInformationDemo",
  "combinedAndOrDemo", "convertSQLQueryDemo", "copyThisCollectionToSampleDatabaseDemo",
  "countOrSizeDemo", "distinctOnMultipleFieldsDemo", "documentWithAParticularFieldValueDemo",
  "employee", "employeeInformation", "findListOfIdsDemo", "findMimimumElementInArrayDemo",
  "findSubstring", "getAllRecordsFromSourceCollectionDemo", "getElementWithMaxIdDemo",
  "insertDocumentWithDateDemo", "internalArraySizeDemo", "largestDocumentDemo",
  "makingStudentInformationClone", "nestedArrayDemo", "oppositeAddToSetDemo",
  "prettyDemo", "projectionAnElementDemo", "replacingEntireDocumentDemo",
  "returnOnlyUniqueValuesDemo", "searchInInnerDemo", "selectItemDemo",
  "selectWhereInDemo", "sourceCollection", "specificFieldDemo", "studentInformation",
  "sumOfValueDemo", "sumTwoFieldsDemo", "truncateDemo", "updateFieldIfValueIsGreaterDemo",
  "updateInformation", "updateSubObjectDemo", "userInformation"
]

คำสั่งย่อ (Shortcuts)

  • show dbs - แสดงฐานข้อมูลทั้งหมด (เหมือน listDatabases)
  • show collections - แสดงคอลเลกชันในฐานข้อมูลปัจจุบัน (เหมือน getCollectionNames)
  • db.getCollectionInfos() - แสดงข้อมูลรายละเอียดคอลเลกชัน (options, indexes, etc.)

หมายเหตุ

  • ต้องอยู่ในฐานข้อมูล admin ถึงจะใช้ listDatabases ได้
  • ฐานข้อมูล admin, config, local เป็น System Databases
  • sizeOnDisk แสดงขนาดไฟล์บนดิสก์ (bytes)
  • empty: true หมายถึงฐานข้อมูล/คอลเลกชันว่างเปล่า