Node.js MongoDB コレクション作成
MongoDBにおけるコレクション(Collection)は、MySQLなどのリレーショナルデータベースにおけるテーブル(Table)に相当する概念です。
1. コレクションの作成
MongoDBで新しくコレクションを作成するには、createCollection() メソッドを使用します。
1.1 実装例:「customers」コレクションの作成
以下のコードは、mydb データベース内に customers という名前のコレクションを作成する例です。
let MongoClient = require('mongodb').MongoClient;
let url = "mongodb://localhost:27017/";
// MongoDBサーバーへ接続
MongoClient.connect(url, function(err, db) {
if (err) throw err;
// 操作対象のデータベース "mydb" を指定
let dbo = db.db("mydb");
// "customers" コレクションを作成
dbo.createCollection("customers", function(err, res) {
if (err) throw err;
console.log("コレクションが作成されました!");
// 処理完了後に接続を閉じる
db.close();
});
});2. プログラムの実行
上記の内容を demo_mongodb_createcollection.js というファイル名で保存し、コマンドラインから実行してください。
demo_mongodb_createcollection.js の実行
C:\Users\Your Name>node demo_mongodb_createcollection.js正常に処理されると、ターミナルに以下の結果が表示されます。
Collection created!3. 【重要】コレクションが作成されるタイミング
MongoDBのデータベース作成時と同様に、コレクションもコンテンツ(内容)が追加されるまで、物理的には作成されません。
MongoDBは、少なくとも1つのドキュメント(Document)が挿入されるまで、実際のコレクションの生成を待機する仕様となっています。開発時には、空のコレクションを作成しただけではGUIツールなどで確認できない場合がある点に注意してください。