How to Setup MongoDB on Mac
This blog shows how to set up MongoDB 4.4 Community version on Mac OS, also will create a simple database, table, and collection, and how to backup and store data by using mongoexport and mongoimport.
Install MongoDB Server
Install MongoDB on Mac is a little different compare to the Mac, you'll need brew to install the MongoDB, on this blog assume brew is already installed on Mac.
Download Homebrew formula for MongoDB
brew tap mongodb/brew
Install MongoDB in macOS
brew install firstname.lastname@example.org
Install MongoDB Tools
Starting from MongoDB 4.4, use brew will also install the mongodump, mongoexport, mongoimport and some other commands.
Install MongoDB Compass
MongoDB Compass is the GUI tool, you should install on your local development environment so you can connect to the MongoDB server and run the query from GUI.
To install MongoDB Compass on macOS, you'll go to the official site here to download the dmg file and install it on your macOS.
To connect to the localhost MongoDB instance just enter the following URL at MongoDB Compass UI.
Create Database, Collection, and Record
After you install MongoDB Compass and connect to the localhost MongoDB instance, you should be able to easily create a new database, collection, and record.
You could also use the command line or the MONGOSH BETA command line window at the Compass UI.
show dbs use myNewDatabase
First show dbs will list all the databases, the use myNewDtabase will create a database but you won't see it until you add a new collection.
Create Table and Record
This command will create a new table myUser and insert a new record into the collection.
MongoDB Backup and Restore Data
At this point, you can MongoDB server installed and able to create a database and collection, next I'd like to try to backup and restore data by using mongoexport and mongoimport. The mongoexport will export the data from MongoDB as JSON file, then use mongoimport can import the JSON file into the MongoDB.
This will work in a small development environment, as you want to export a list of data then dump it into another environment from this JSON file.
Use Mongoexport to export data to JSON
First, cd to the location that has the mongoexport executable file then run the following command.
mongoexport --collection=myUser --db=myDB --out=myUser.json
This command will look up the myDB database's myUser collection, then output the whole result into myUser.json file.
Use Mongoimport to import data to the existing MongoDB Server
Following command will use myUser.json and then override the myUser collection, used mode as upsert so any existing same record will be replaced.
mongoimport --collection=myUser --db=myDB --file=myUser.json --mode=upsert