-
Notifications
You must be signed in to change notification settings - Fork 280
/
Copy pathmongo.ts
45 lines (35 loc) · 1.12 KB
/
mongo.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* @title Connect to MongoDB
* @difficulty intermediate
* @tags cli, deploy
* @run -N -S -R <url>
* @resource {https://deno.land/x/mongo} Deno MongoDB on deno.land/x
* @group Databases
*
* Using the Deno MongoDB client, you can connect to a Mongo database
* running anywhere.
*/
import { MongoClient } from "npm:[email protected]";
// Create a new instance of the MongoDB client running locally on port 27017
const client = new MongoClient("mongodb://127.0.0.1:27017");
// 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<DinosaurSchema>("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();
console.log(allDinosaurs);
// Close the MongoDB client connection
client.close();