MongoDB
 Computer >> コンピューター >  >> プログラミング >> MongoDB

【MongoDB】すべてのデータベースから全コレクションを一括取得する方法

MongoDBの全データベースから全コレクションを取得する手順

MongoDBサーバー上に存在するすべてのデータベースのすべてのコレクションを一覧で取得したい場合があります。これを実現するには、大きく分けて次の2段階の手順を踏みます。

  1. listDatabasesコマンドでサーバー上の全データベース名を取得する
  2. forEach()ループで各データベースに切り替えながら、getCollectionNames()でコレクション名を取得・出力する

ステップ1:すべてのデータベース名を取得する

まず、getSiblingDB()メソッドを使ってadminデータベースへの参照を取得し、そこでlistDatabases管理コマンドを実行します。次のクエリをMongoDBシェルで実行してください。

> switchDatabaseAdmin = db.getSiblingDB("admin");
admin
> allDatabaseName = switchDatabaseAdmin.runCommand({ "listDatabases": 1 }).databases;

実行すると、各データベースの「名前(name)」「ディスク上のサイズ(sizeOnDisk)」「空かどうか(empty)」の情報を持つ配列が返されます。

[
    {
        "name" : "admin",
        "sizeOnDisk" : 495616,
        "empty" : false
    },
    {
        "name" : "config",
        "sizeOnDisk" : 98304,
        "empty" : false
    },
    {
        "name" : "local",
        "sizeOnDisk" : 73728,
        "empty" : false
    },
    {
        "name" : "sample",
        "sizeOnDisk" : 1335296,
        "empty" : false
    },
    {
        "name" : "sampleDemo",
        "sizeOnDisk" : 278528,
        "empty" : false
    },
    {
        "name" : "studentSearch",
        "sizeOnDisk" : 262144,
        "empty" : false
    },
    {
        "name" : "test",
        "sizeOnDisk" : 8724480,
        "empty" : false
    }
]

ステップ2:各データベースのコレクション名を取得して出力する

続いて、ステップ1で取得したデータベース情報の配列をforEach()でループ処理し、getSiblingDB()で対象データベースに切り替えたうえで、getCollectionNames()によってコレクション名の一覧を取得します。あとはprint()でコンソールに出力するだけです。

> allDatabaseName.forEach(function(databaseName)
... {
...     db = db.getSiblingDB(databaseName.name);
...     collectionName = db.getCollectionNames();
...     collectionName.forEach(function(collectionName)
...     {
...         print(collectionName);
...     });
... });

このスクリプトを実行すると、サーバー上の全データベースに含まれるすべてのコレクション名が順番に出力されます。以下は実際の実行結果の例です。

clearingItemsInNestedArrayDemo
customIdDemo
deleteRecordDemo
documentExistsOrNotDemo
findAllExceptFromOneOrtwoDemo
mongoExportDemo
startup_log
arraySizeErrorDemo
basicInformationDemo
copyThisCollectionToSampleDatabaseDemo
deleteAllRecordsDemo
deleteDocuments
deleteDocumentsDemo
deleteSomeInformation
documentWithAParticularFieldValueDemo
employee
findListOfIdsDemo
findSubstring
getAllRecordsFromSourceCollectionDemo
getElementWithMaxIdDemo
internalArraySizeDemo
largestDocumentDemo
makingStudentInformationClone
oppositeAddToSetDemo
prettyDemo
returnOnlyUniqueValuesDemo
selectWhereInDemo
sourceCollection
studentInformation
sumOfValueDemo
truncateDemo
updateInformation
userInformation
copyThisCollectionToSampleDatabaseDemo
deleteDocuments
deleteDocumentsDemo
deleteInformation
employee
internalArraySizeDemo
prettyDemo
sourceCollection
updateInformation
userInformation
col1
col2
indexingForArrayElementDemo
removeObjectFromArrayDemo
specifyAKeyDemo
useVariableDemo
ConvertStringToDateDemo
Employee_Information
IdUpdateDemo
IndexingDemo
NotAndDemo
ProductsInformation
addCurrentDateTimeDemo
addFieldDemo
addNewFieldToEveryDocument
aggregateSumDemo
aggregationFrameworkWithOrMatchDemo
aggregationSortDemo
andOrDemo
arrayInnerElementsDemo
arrayLengthGreaterThanOne
arrayOfArraysDemo
avoidDuplicateEntriesDemo
caseInsensitiveDemo
caseInsesitiveDemo
castingDemo
changeDataType
changeType
charactersAllowedDemo
charactersDemo
checkFieldContainsStringDemo
checkFieldExistsOrNotDemo
checkSequenceDemo
collectionOnDifferentDocumentDemo
combinationOfArrayDemo
comparingTwoFieldsDemo
concatStringAndIntDemo
conditionalSumDemo
convertStringToNumberDemo
copyThisCollectionToSampleDatabaseDemo
countDemo
countPerformanceDemo
createSequenceDemo
creatingUniqueIndexDemo
dateDemo
deleteAllElementsInArrayDemo
deleteRecordDemo
demo.insertCollection
distinctAggregation
distinctCountValuesDemo
distinctRecordDemo
distinctWithMultipleKeysDemo
doubleNestedArrayDemo
embeddedCollectionDemo
employeeInformation
equivalentForSelectColumn1Column2Demo
fieldIsNullOrNotSetDemo
filterArray
findAllDuplicateKeyDocumentDemo
findAllNonDistinctDemo
findByMultipleArrayDemo
findDocumentDoNotHaveCertainFields
findDocumentNonExistenceFieldDemo
findDocumentWithObjectIdDemo
findDuplicateByKeyDemo
findDuplicateRecordsDemo
findMinValueDemo
findSpecificValue
findValueInArrayWithMultipleCriteriaDemo
firstDocumentDemo
firstItemInArrayToNewFieldDemo
getDistinctListOfSubDocumentFieldDemo
getFirstItemDemo
getIndexSizeDemo
getLastNRecordsDemo
getLastXRecordsDemo
getNThElementDemo
getParticularElementFromArrayDemo
getPartuclarElement
getSizeDemo
getSizeOfArray
gettingHighestValueDemo
groupByDateDemo
hideidDemo
identifyLastDocuementDemo
incrementValueDemo
incrementValueInNestedArrayDemo
indexDemo
indexOptimizationDemo
indexTimeDemo
index_Demo
indexingDemo
insertDemo
insertFieldWithCurrentDateDemo
insertIfNotExistsDemo
insertIntegerDemo
insertOneRecordDemo
listAllValuesOfCeratinFieldsDemo
matchBetweenFieldsDemo
mongoExportDemo
multipleOrDemo
my-collection
nestedArrayDemo
nestedIndexDemo
nestedObjectDemo
new_Collection
notLikeOpeartorDemo
numberofKeysInADocumentDemo
objectInAnArrayDemo
objectidToStringDemo
orConditionDemo
orDemo
orderDocsDemo
paginationDemo
performRegex
priceStoredAsStringDemo
priceStoredDemo
queryArrayElementsDemo
queryByKeyDemo
queryBySubFieldDemo
queryForBooleanFieldsDemo
queryInSameDocumentsDemo
queryToEmbeddedDocument
queryingMongoDbCaseInsensitiveDemo
regExpOnIntegerDemo
regexSearchDemo
removeArrayDemo
removeArrayElement
removeArrayElementByItsIndexDemo
removeArrayElements
removeDocumentOnBasisOfId
removeDuplicateDocumentDemo
removeDuplicateDocuments
removeElementFromDoublyNestedArrayDemo
removeFieldCompletlyDemo
removeMultipleDocumentsDemo
removeObject
removingidElementDemo
renameFieldDemo
retrieveValueFromAKeyDemo
retunFieldInFindDemo
returnQueryFromDate
reverseRegexDemo
s
searchArrayDemo
searchDocumentDemo
searchDocumentWithSpecialCharactersDemo
searchMultipleFieldsDemo
secondDocumentDemo
selectInWhereIdDemo
selectMongoDBDocumentsWithSomeCondition
selectRecordsHavingKeyDemo
selectSingleFieldDemo
singleFieldDemo
sortDemo
sortInnerArrayDemo
sortingDemo
sourceCollection
sqlLikeDemo
stringFieldLengthDemo
stringToObjectIdDemo
test.js
translateDefinitionDemo
unconditionalUpdatesDemo
uniqueIndexOnArrayDemo
unprettyJsonDemo
unwindOperatorDemo
updateDemo
updateExactField
updateIdDemo
updateManyDocumentsDemo
updateNestedValueDemo
updateObjects
updatingEmbeddedDocumentPropertyDemo
userStatus

使用しているコマンドのポイント

  • db.getSiblingDB("admin"):現在の接続先を変更せずに、指定した別のデータベースへの参照を取得できる便利なメソッドです。
  • runCommand({ "listDatabases": 1 }):サーバー上の全データベースの名前・サイズ・emptyフラグを返す管理コマンドです。adminデータベースに対して実行する必要があります。
  • db.getCollectionNames():現在参照しているデータベース内の全コレクション名を配列として返します。
  • print():MongoDBシェルのコンソールに文字列を出力します。

なお、adminやconfig、localといったシステム用データベースも結果に含まれるため、アプリケーション用のコレクションだけを抽出したい場合は、データベース名やコレクション名のフィルタリング条件をforEach()内に追加するとよいでしょう。

  1. Matplotlibのプロットからすべての凡例を取得するにはどうすればよいですか?

    Matplotlibのプロットからすべての凡例(Legend)を取得するには、get_children()メソッドを使って軸が持つすべてのプロパティ(子要素)を取得し、それらを順番に反復処理します。各要素がLegendクラスのインスタンスであるかどうかを判定し、該当する場合はその凡例テキストを取り出すことができます。手順図のサイズを設定し、autolayoutを有効にしてサブプロット間や図の周囲の余白を自動調整します。numpyを使ってx軸用のデータポイントを作成します。図(figure)とサブプロット(axes)を作成します。plot()メソッドを使い、ラベルと色を変えてsin(x)とcos

  2. Pythonの辞書からすべてのキーをリストとして取得する方法

    Pythonの辞書(dict)からすべてのキーをリストとして取得したい場合、最もシンプルな方法は dict.keys() メソッドを使うことです。このメソッドは辞書内のすべてのキーを含むビューオブジェクトを返すため、list() で囲むことで簡単にリストへ変換できます。keys()メソッドを使う例my_dict = {name: TutorialsPoint, time: 15 years, location: India} key_list = list(my_dict.keys()) print(key_list)出力実行すると、次のような結果が得られます。[name, time, loc