
- Node.js 教程
- Node.js - 首頁
- Node.js - 簡介
- Node.js - 環境設定
- Node.js - 第一個應用程式
- Node.js - REPL 終端
- Node.js - 命令列選項
- Node.js - 包管理器 (NPM)
- Node.js - 回撥函式概念
- Node.js - 上傳檔案
- Node.js - 傳送郵件
- Node.js - 事件
- Node.js - 事件迴圈
- Node.js - 事件發射器
- Node.js - 偵錯程式
- Node.js - 全域性物件
- Node.js - 控制檯
- Node.js - 程序
- Node.js - 應用程式擴充套件
- Node.js - 打包
- Node.js - Express 框架
- Node.js - RESTFul API
- Node.js - 緩衝區
- Node.js - 流
- Node.js - 檔案系統
- Node.js MySQL
- Node.js - MySQL 入門
- Node.js - MySQL 建立資料庫
- Node.js - MySQL 建立表
- Node.js - MySQL 插入資料
- Node.js - MySQL 從表中選擇資料
- Node.js - MySQL Where 條件
- Node.js - MySQL Order By 排序
- Node.js - MySQL 刪除資料
- Node.js - MySQL 更新資料
- Node.js - MySQL 聯接
- Node.js MongoDB
- Node.js - MongoDB 入門
- Node.js - MongoDB 建立資料庫
- Node.js - MongoDB 建立集合
- Node.js - MongoDB 插入資料
- Node.js - MongoDB 查詢資料
- Node.js - MongoDB 查詢
- Node.js - MongoDB 排序
- Node.js - MongoDB 刪除資料
- Node.js - MongoDB 更新資料
- Node.js - MongoDB 限制結果數量
- Node.js - MongoDB 聯接
- Node.js 模組
- Node.js - 模組
- Node.js - 內建模組
- Node.js - 實用程式模組
- Node.js - Web 模組
- Node.js 有用資源
- Node.js - 快速指南
- Node.js - 有用資源
- Node.js - 討論
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 中建立。

您也可以在 MongoDB shell 中驗證相同的內容。
> use mydatabase < switched to db mydatabase > show collections < MyCollection
廣告