MongoDB On macOS
28 May, 2023
2
2
1
Contributors
Install MongoDB on macOS
Installation
install MongoDB on macOS using HomBrew.
Prerequisites
- Install Xcode Command-Line Tools
HomeBrew requires the Xcode command-line
xcode-select --install
- Install HomeBrew
install brew
using the official HomeBrew
Installing MongoDB
- in the console type
brew tap mongodb/brew
> this will add repository mongodb/brew to the list of formulae that HomeBrew track, update, and install from.
- update homebrew and existing formulae type:
brew update
- install mongoDB type:
brew install mongodb-community@{version you want}
note: {version you want} ex: 6.0
Start MongoDB
- run mongoDB as macOS service type:
brew services start mongobd-community@{version you install}
- to stop mongoDB type:
brew services stop mongobd-community@{version you install}
if you want to see the full documentation you can visit mongodb doc
Accessing MongoDB
if MongoDB service has been running with Start MongoDB above
- access MongoDB Database using mongosh:
mongosh
this command will open mongosh command line interface that use to operate database.
Show All Databases
you can use show dbs
command to show all databases in your storage.
show dbs
Switch Between Database
use {databaseName}
example
use cakeStore
-> change {databaseName} to what database you want
-> it can be use to make new database
-> in example, it will createcakeStore
database if not exist
CRUD in MongoDB
CREATE Database, collections, data
- To insert a single document, use
db.collection.insertOne()
. - To insert multiple document, use
db.collection.insertMany()
.
example insert a single document
cake.collection.insertOne({
_id: 1,
cakeName: "Chiffon Cake",
price: 2
})
example insert multiple document
cake.collection.insertMany([
{
_id: 2,
cakeName: "Chocolate Cake",
price: 2
},
{
_id: 3,
cakeName: "Apple Cake",
price: 2.5
}
])