deno.com

连接到 MongoDB

使用 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 -N -S -R https://docs.deno.org.cn/examples/scripts/mongo.ts

您找到所需内容了吗?

隐私政策