Skip to content

Instantly share code, notes, and snippets.

@danny-andrews
Last active July 14, 2021 21:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danny-andrews/3689df8abb5dbee9627ab08d89f7687c to your computer and use it in GitHub Desktop.
Save danny-andrews/3689df8abb5dbee9627ab08d89f7687c to your computer and use it in GitHub Desktop.
MongoDB Quickstart

MongoDB Quickstart

Introduction

  1. Read: https://docs.mongodb.com/manual/introduction/
  2. Read: https://docs.mongodb.com/manual/crud/

Installation

  1. $ brew tap mongodb/brew
  2. $ brew install mongodb-community - Installs mongodb server on your machine.1
  3. $ brew services start mongodb-community - Starts mongodb server locally.2
  4. $ npm install mongodb - Installs mongodb node package.

Usage

db/mongo-config.js:

const { MongoClient } = require("mongodb");

const URI = "mongodb://localhost:27017/";

const insertStuff = async () => {
  const client = await new MongoClient(URI).connect();
  const db = client.db("fec");
  const collection = db.collection("items");
  await collection.insertOne({ name: "stuff" });
  
  // You have to close the connection, or the app will hang.
  // You'll probably want to do this in an afterAll hook in your tests.
  await client.close();
};

insertStuff();

References

  1. Bulk writes: https://docs.mongodb.com/manual/core/bulk-write-operations/
  2. API Docs: https://mongodb.github.io/node-mongodb-native/4.0/
  3. Shell Docs: https://docs.mongodb.com/mongodb-shell/connect/#std-label-mdb-shell-connect

1Linux instructions here.

2By default, this will run on localhost:27017.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment