• Node.js Video Tutorials

Node.js - MongoDB 建立集合



MongoDB 資料庫由一個或多個集合組成。集合是一組文件物件。在 MongoDB 伺服器(獨立伺服器或 MongoDB Atlas 中的共享叢集)上建立資料庫後,您可以在其中建立集合。Node.js 的 mongodb 驅動程式有一個 cerateCollection() 方法,它返回一個 Collection 物件。

MongoDB 中的集合類似於關係資料庫中的表。但是,它沒有預定義的模式。集合中的每個文件可能包含可變數量的鍵值對,並且每個文件中的鍵不一定相同。

要建立集合,請從資料庫連接獲取資料庫物件並呼叫 createCollection() 方法。

db.createCollection(name: string, options)

要建立的集合的名稱作為引數傳遞。該方法返回一個 Promise。集合名稱空間驗證在伺服器端執行。

const dbobj = await client.db(dbname);
const collection = await dbobj.createCollection("MyCollection");

請注意,即使在插入之前沒有建立集合,當您向其中插入文件時,也會隱式建立該集合。

const result = await client.db("mydatabase").collection("newcollection").insertOne({k1:v1, k2:v2});

示例

以下 Node.js 程式碼在名為 mydatabase 的 MongoDB 資料庫中建立一個名為 MyCollection 的集合。

const {MongoClient} = require('mongodb');

async function main(){

   const uri = "mongodb://:27017/";

   const client = new MongoClient(uri);

   try {
      // Connect to the MongoDB cluster
      await client.connect();
        
      await newcollection(client, "mydatabase");
   } finally {
      // Close the connection to the MongoDB cluster
      await client.close();
   }
}

main().catch(console.error);


async function newcollection (client, dbname){
   const dbobj = await client.db(dbname);
   const collection = await dbobj.createCollection("MyCollection");
   console.log("Collection created");
   console.log(collection);
}

MongoDB Compass 顯示 MyCollection 已在 mydatabase 中建立。

MyCollection

您也可以在 MongoDB shell 中驗證相同的內容。

> use mydatabase
< switched to db mydatabase
> show collections
< MyCollection
廣告