deno.com

連線到 MongoDB

在 Github 上編輯

使用 Deno MongoDB 用戶端,您可以連線到在任何地方執行的 Mongo 資料庫。

import { MongoClient } from "npm:mongodb@6.1.0";
建立在本機 27017 埠上執行之 MongoDB 用戶端的新執行個體
const client = new MongoClient("mongodb://127.0.0.1:27017");
連線到 MongoDB 伺服器
await client.connect();
定義集合的結構描述
interface DinosaurSchema {
  name: string;
  skills: string[];
}
存取資料庫
const db = client.db("animals");
存取資料庫內的集合
const dinosaurs = db.collection<DinosaurSchema>("dinosaurs");
將新文件插入集合中
await dinosaurs.insertOne({
  name: "deno",
  skills: ["dancing", "hiding"],
});
使用篩選器尋找集合中的所有文件
const allDinosaurs = await dinosaurs.find({ name: "deno" }).toArray();

console.log(allDinosaurs);
關閉 MongoDB 用戶端連線
client.close();

在本機使用 Deno CLI 執行此範例

deno run --allow-net --allow-sys --allow-read https://deno-docs.dev.org.tw/examples/scripts/mongo.ts

您找到需要的資訊了嗎?

隱私權政策