Mongodb 系列教程
- Mongodb的實踐一:初始(包括安裝)
- Mongodb的實踐二:
- Mongodb的實踐三
- Mongodb的實踐四
- Mongodb的實踐五
- Mongodb的實踐六
- Mongodb的實踐七
- Mongodb的實踐八
序言
Mongodb 教程其實早在一年前就一直想寫一寫,因爲工作比較忙,自己也沒有真的大量用於真實項目裏的實踐,一直耽擱了
簡介
MongoDB是一個基於分佈式文件存儲的數據庫.
官網
https://www.mongodb.com/downl...
單機安裝
三種安裝支持
1. window安裝可參考
2. 類unix系下安裝
wget https://fastdl.mongodb.org/osx/mongodb-osx-ssl-x86_64-4.0.6.tgz
tar zxvf mongodb-osx-ssl-x86_64-4.0.6.tgz
cd mongodb-osx-ssl-x86_64-4.0.6/bin
mongod --config /xx/xx.config --fork
3. docker安裝
# -p local_port:docker_port
docker pull mongo:4.1.5
docker run -d --name mongodb-4.1.5 -e MONGO_INITDB_ROOT_USERNAME=root -e MONGO_INITDB_ROOT_PASSWORD=123456 -v /data/mongodb/docker/4.1.5:/mongodb -v /data/mongodb/docker/4.1.5/conf.d:/etc/mongo -p 27077:27017 mongo:4.1.5 --config /etc/mongo/mongod.conf --auth
docker 目錄結構
├── conf.d
│ └── mongod.conf
├── data
└── logs
mongod.conf
/data/mongodb/docker/4.1.5/conf.d下的mongo配置文件
# mongod.conf
# for documentation of all options, see:
# http://docs.mongodb.org/manual/reference/configuration-options/
# Where and how to store data.
storage:
dbPath: /mongodb/data
journal:
enabled: true
# engine:
# mmapv1:
# wiredTiger:
# where to write logging data.
systemLog:
destination: file
logAppend: true
path: /mongodb/logs/mongod.log
# network interfaces
net:
port: 27017
# bindIp: 127.0.0.1
# bindIp: 0.0.0.0
# how the process runs
processManagement:
timeZoneInfo: /usr/share/zoneinfo
security:
authorization: enabled
#operationProfiling:
#replication:
#sharding:
## Enterprise-Only Options:
#auditLog:
#snmp:
連接測試
mongo --host 127.0.0.1 --port 27077
> db.auth("root", "123456")
1
> show dbs;
admin 0.000GB
config 0.000GB
local 0.000GB
創建新數據和賬號
> use demo;
switched to db demo
> db.createUser({
... user : "demo",
... pwd: "123456",
... roles : [
... {
... "role" : "dbAdmin",
... "db" : "demo"
... },
... {
... "role" : "dbOwner",
... "db" : "demo"
... }
... ],
... "mechanisms" : [
... "SCRAM-SHA-1",
... "SCRAM-SHA-256"
... ]
... });
Successfully added user: {
"user" : "demo",
"roles" : [
{
"role" : "dbAdmin",
"db" : "demo"
},
{
"role" : "dbOwner",
"db" : "demo"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
> exit;
測試插入和查詢
# 需要重連
mongo --host 127.0.0.1 --port 27077
>db.auth("demo","123456");
1
> db
demo
> db.foo.insert({"name":"qkl",age:"18",sex:1});
WriteResult({ "nInserted" : 1 })
> show dbs;
demo 0.000GB
> show collections;
foo
> db.foo.find({})
{ "_id" : ObjectId("5d22db4bbcbb35d902a31a92"), "name" : "qkl", "age" : "18", "sex" : 1 }
> db.foo.insert({"name":"hax",age:"16",sex:0});
WriteResult({ "nInserted" : 1 })
> db.foo.find({})
{ "_id" : ObjectId("5d22db4bbcbb35d902a31a92"), "name" : "qkl", "age" : "18", "sex" : 1 }
{ "_id" : ObjectId("5d22dbafbcbb35d902a31a93"), "name" : "hax", "age" : "16", "sex" : 0 }