deno.com

连接到 MongoDB

在 GitHub 上编辑

使用 Deno MongoDB 客户端,您可以连接到任何地方运行的 Mongo 数据库。

import { MongoClient } from "npm:[email protected]";
创建在端口 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://docs.deno.org.cn/examples/scripts/mongo.ts

您找到所需的信息了吗?

隐私政策