Connect to MongoDB


Using the Deno MongoDB client, you can connect to a Mongo database running anywhere.

import { MongoClient } from "npm:mongodb@6.1.0";
Create a new instance of the MongoDB client running locally on port 27017
const client = new MongoClient("mongodb://");
Connect to the MongoDB server
await client.connect();
Define the schema for the collection
interface DinosaurSchema {
  name: string;
  skills: string[];
Access the database
const db = client.db("animals");
Access the collection within the database
const dinosaurs = db.collection("dinosaurs");
Insert a new document into the collection
await dinosaurs.insertOne({
  name: "deno",
  skills: ["dancing", "hiding"],
Find all documents in the collection with the filter
const allDinosaurs = await dinosaurs.find({ name: "deno" }).toArray();

Close the MongoDB client connection

Run this example locally using the Deno CLI:

deno run --allow-net --allow-sys --allow-read

Additional resources: