1.What’s MongoDB?
MongoDB is a document database which belongs to a family of databases called NoSQL – not only SQL. In MongoDB, records are documents which behave a lot like JSON objects in JavaScript. Values in documents can be looked up by their field’s key. Documents can have some fields/keys and not others, which makes Mongo extremely flexible.
This is different than SQL databases like MySQL and PostgreSQL, where fields correspond to columns in a table and individual records correspond to rows.
2. Install and Run MongoDB with Homebrew
- Open the Terminal app and type
brew update
. - After updating Homebrew
brew install mongodb
-
The install creates:
the configuration file (/usr/local/etc/mongod.conf
)systemLog: destination: file path: /usr/local/var/log/mongodb/mongo.log logAppend: true storage: dbPath: /usr/local/var/mongodb net: bindIp: 127.0.0.1
the log directory path (
/usr/local/var/log/mongodb
)
the data directory path (/usr/local/var/mongodb
)
3. Run the MongoDB daemon
In one of your terminal windows run mongod
. This should start the Mongo server.
Oops, something is wrong:
[main] Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'
[initandlisten] MongoDB starting : pid=13410 port=27017 dbpath=/data/db 64-bit host=Zhihuis-Mac-mini.local
[initandlisten] db version v4.0.3
[initandlisten] git version: 7ea530946fa7880364d88c8d8b6026bbc9ffa48c
[initandlisten] allocator: system
[initandlisten] modules: none
[initandlisten] build environment:
[initandlisten] distarch: x86_64
[initandlisten] target_arch: x86_64
[initandlisten] options: {}
[initandlisten] exception in initAndListen: NonExistentPath: Data directory /data/db not found., terminating
[initandlisten] shutdown: going to close listening sockets...
[initandlisten] removing socket file: /tmp/mongodb-27017.sock
[initandlisten] now exiting
[initandlisten] shutting down with code:100
It complains that exception in initAndListen: NonExistentPath: Data directory /data/db not found.
You can either
-
create the db folder manually by
mkdir -p /data/db
, Make sure that the /data/db directory has the right permissions by running> sudo chown -R `id -un` /data/db > # Enter your password
or
-
Specify the mongod.conf when Running the daemon
mongod --config /usr/local/etc/mongod.conf
. The db file locates in/usr/local/var/log/mongodb
Alternatively, to run MongoDB as a macOS service, issue the following (the process uses the /usr/local/etc/mongod.conf file, created during the install):
brew services start mongodb
4. Connect and Use MongoDB
mongo
5. Exit/Stop the Mongo
To exit the Mongo shell run quit()
To stop the Mongo daemon hit ctrl-c