MongoDB Node.js 資料庫互動
Node.js 資料庫互動
在本教程中,我們將使用 MongoDB Atlas 資料庫。如果您還沒有 MongoDB Atlas 賬戶,可以免費在 MongoDB Atlas 註冊。
我們還將使用來自 聚合介紹 部分的示例資料載入的 "sample_mflix" 資料庫。
MongoDB Node.js Driver 安裝
要在 Node.js 中使用 MongoDB,您需要在 Node.js 專案中安裝 mongodb
包。
在終端中使用以下命令安裝 mongodb
包
npm install mongodb
現在我們可以使用此包連線到 MongoDB 資料庫。
在專案目錄中建立一個 index.js
檔案。
index.js
const { MongoClient } = require('mongodb');
連線字串
為了連線到我們的 MongoDB Atlas 資料庫,我們需要從 Atlas 儀表盤獲取連線字串。
轉到 **Database**,然後點選叢集上的 **CONNECT** 按鈕。
選擇 **Connect your application**,然後複製您的連線字串。
示例: mongodb+srv://<username>:<password>@<cluster.string>.mongodb.net/myFirstDatabase?retryWrites=true&w=majority
您需要將 <username>
、<password>
和 <cluster.string>
替換為您的 MongoDB Atlas 使用者名稱、密碼和叢集字串。
連線到 MongoDB
讓我們新增到 index.js
檔案中。
index.js
const { MongoClient } = require('mongodb');
const uri = "<Your Connection String>";
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
const db = client.db('sample_mflix');
const collection = db.collection('movies');
// Find the first document in the collection
const first = await collection.findOne();
console.log(first);
} finally {
// Close the database connection when finished or an error occurs
await client.close();
}
}
run().catch(console.error);
自己動手試一試 »
在終端中執行此檔案。
node index.js
您應該會在控制檯中看到第一個文件被記錄下來。
CRUD & 文件聚合
就像我們使用 mongosh
一樣,我們可以使用 MongoDB Node.js 語言驅動程式在資料庫中建立、讀取、更新、刪除和聚合文件。
基於之前的示例,我們可以將 collection.findOne()
替換為 find()
、insertOne()
、insertMany()
、updateOne()
、updateMany()
、deleteOne()
、deleteMany()
或 aggregate()
。
嘗試其中一些。