コマンド例の実行
インスタンスで コマンド() メソッドを使用してデータベースコマンドを実行できます。Db
ドキュメント内で コマンドと オプションを指定できます。 コマンドを実行するには、このドキュメントをcommand()
メソッドに渡します。 データベースコマンドの完全なリストを表示するには、サーバー マニュアルの「データベースコマンド」を参照してください。
Tip
可能な場合は常に Node.js ドライバーの代わりにMongoDB Shellを管理タスクに使用します。
RunCommandOptions
オブジェクトをcommand()
メソッドに渡すことで、任意のコマンド動作を指定できます。 サポートされているオプションの詳細については、 Db.command() API ドキュメント を参照してください。
例
注意
この例を使用して、MongoDB のインスタンスに接続し、サンプルデータを含むデータベースと交流できます。MongoDB インスタンスへの接続とサンプルデータセットの読み込みの詳細については、 使用例ガイドを参照してください。
1 /* Run a database command */ 2 3 import { MongoClient } from "mongodb"; 4 5 // Replace the uri string with your MongoDB deployment's connection string 6 const uri = "<connection string uri>"; 7 8 const client = new MongoClient(uri); 9 10 async function run() { 11 try { 12 // Get the "sample_mflix" database 13 const db = client.db("sample_mflix"); 14 15 // Find and print the storage statistics for the "sample_mflix" database using the 'dbStats' command 16 const result = await db.command({ 17 dbStats: 1, 18 }); 19 console.log(result); 20 } finally { 21 // Close the database connection on completion or error 22 await client.close(); 23 } 24 } 25 run().catch(console.dir);
1 /* Run a database command */ 2 3 import { MongoClient } from "mongodb"; 4 5 // Replace the uri string with your MongoDB deployment's connection string 6 const uri = "<connection string uri>"; 7 8 const client = new MongoClient(uri); 9 10 async function run() { 11 try { 12 // Get the "sample_mflix" database 13 const db = client.db("sample_mflix"); 14 15 // Find and print the storage statistics for the "sample_mflix" database using the 'dbStats' command 16 const result = await db.command({ 17 dbStats: 1, 18 }); 19 console.log(result); 20 } finally { 21 // Close the database connection on completion or error 22 await client.close(); 23 } 24 } 25 run().catch(console.dir);
注意
同一のコードスニペット
上記の JavaScript と TypeScript のコード スニペットは同一です。このユースケースに関連するドライバーの TypeScript 固有の機能はありません。
上記のコマンドを実行すると、次の出力が表示されます。
{ db: 'sample_mflix', collections: 6, views: 0, objects: 75620, ... }