Skip to content

Instantly share code, notes, and snippets.

@jbergant
Created July 1, 2020 14:13
Show Gist options
  • Select an option

  • Save jbergant/ba1bdd047d5e2a3359a33357d1cff7f8 to your computer and use it in GitHub Desktop.

Select an option

Save jbergant/ba1bdd047d5e2a3359a33357d1cff7f8 to your computer and use it in GitHub Desktop.
Deno with MongoDb examples
import { MongoClient } from "https://deno.land/x/[email protected]/mod.ts";
interface Course {
_id: { $oid: string };
title: string;
author: string;
rating: number;
}
const client = new MongoClient();
client.connectWithUri(
"mongodb+srv://janathebot:[email protected]/janathebot?retryWrites=true",
);
const db = client.database("databasename");
const coursesDB = db.collection("collectionname");
const insertId = await coursesDB.insertOne({
title: "Chatbots",
author: "Jana Bergant",
rating: 9,
});
const insertIds = await coursesDB.insertMany([
{
title: "Chatbots",
author: "Jana Bergant",
rating: 9,
},
{
title: "Google Assistant app",
author: "Jana Bergant",
rating: 8,
},
{
title: "Blog with Jekyll",
author: "Jana Bergant",
rating: 8,
},
]);
console.log(insertIds);
// Read all records
const courses = await coursesDB.find({ title: { $ne: null } });
// Find Chatbots course
const course = await coursesDB.find({ title: "Chatbots" });
console.log(course);
// Find all except Chatbots course
const courses = await coursesDB.find({ title: { $ne: "Chatbots" } });
console.log(courses);
// Find by id:
const course = await coursesDB.find({ _id: { "$oid": "enterid" } },);
console.log(course);
// Count all courses:
const count = await coursesDB.count({ title: { $ne: null } });
console.log(count);
Update one course, find it by title:
const { matchedCount, modifiedCount, upsertedId } = await coursesDB.updateOne(
{ title: "Chatbots"},
{ $set: { rating: 5 } },
);
console.log(matchedCount);
console.log(modifiedCount);
console.log(upsertedId);
// Delete course by title:
const deleteCount = await coursesDB.deleteOne({ title: "Chatbots" });
console.log(deleteCount);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment