Skip to content

Instantly share code, notes, and snippets.

@phortuin
Last active October 5, 2021 17:54
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 phortuin/1ebf951acd74023649b8f12fd6861a34 to your computer and use it in GitHub Desktop.
Save phortuin/1ebf951acd74023649b8f12fd6861a34 to your computer and use it in GitHub Desktop.
Set up mongo + database on MacOS (M1)

Based on these instructions.

Install with Homebrew:

$ brew tap mongodb/brew
$ brew install mongodb-community

Run server:

$ mongod --config /opt/homebrew/etc/mongod.conf

Note: if you’re on Intel, the /opt/homebrew probably is /usr/local.

The mongo daemon mongod is eerily quiet, but it should run. To open the Mongo shell:

$ mongosh

In the Mongo shell, you can see which databases exist:

test> show dbs

Which should print:

admin     41 kB
config  12.3 kB
local   73.7 kB

To ‘create’ a database, use the use command. Note that it won’t turn up in show dbs until it actually has content:

test> use mydatabase
switched to db mydatabase

Now a collection (what would be a table in relational databases) can be created (if you wish, you can add documents right in the root of the database as well):

mydatabase> db.createCollection('mycollection')
{ ok: 1 }
mydatabase> show collections
mycollection

Yay, it exists! To add a document to the collection and list all documents:

mydatabase> db.mycollection.insertOne({ hello: 'world' })
{
  acknowledged: true,
  insertedId: ObjectId("615b57647f0fbadc9644f10a")
}
mydatabase> db.mycollection.find({})
[
  { _id: ObjectId("615b57647f0fbadc9644f10a"), hello: 'world' }
]

Ain’t that grand. To quit the Mongo shell:

mydatabase> quit

Finally, in a .env file for Node.js software development, your database connection string should look like this:

MONGO_URI=mongodb://127.0.0.1:27017

More complex connection strings are available, ofcourse.

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