如何在 MongoDB 服务器上获得一个数据库和集合的列表?
若要获取所有数据库的列表,需要使用以下语法 -
use admin db.runCommand({listDatabases: 1});
若要获取特定数据库的所有集合名称的列表,需要使用以下语法 -
use yourDatabaseName; db.getCollectionNames();
让我们实现以上语法 -
情况 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 - 获取集合列表
在此,我们获取“sample”数据库的集合列表
> use sample; switched to db sample > db.getCollectionNames();
这会产生以下输出 -
[ "arraySizeErrorDemo", "basicInformationDemo", "copyThisCollectionToSampleDatabaseDemo", "documentWithAParticularFieldValueDemo", "employee", "findListOfIdsDemo", "findMimimumElementInArrayDemo", "findSubstring", "getAllRecordsFromSourceCollectionDemo", "getElementWithMaxIdDemo", "insertDocumentWithDateDemo", "internalArraySizeDemo", "largestDocumentDemo", "makingStudentInformationClone", "nestedArrayDemo", "oppositeAddToSetDemo", "prettyDemo", "returnOnlyUniqueValuesDemo", "selectItemDemo", "selectWhereInDemo", "sourceCollection", "specificFieldDemo", "studentInformation", "sumOfValueDemo", "sumTwoFieldsDemo", "truncateDemo", "updateFieldIfValueIsGreaterDemo", "updateInformation", "userInformation" ]
广告