mongodb 教程

mongodb 使用教程

一、配置並訪問資料庫

1. 配置資料庫參數mongod.conf

systemLog:   #配置系統日誌,記錄系統的啟動記錄、錯誤日誌
  destination: file   #配置日誌的保存方式
  logAppend: true     #配置文件追加模式
  path: /var/log/mongodb/mongod.log   #日誌路徑

# Where and how to store data.
storage:
  dbPath: /var/lib/mongo   
  journal:
    enabled: true
#  engine:
#  wiredTiger:

# how the process runs
processManagement:
  fork: true  # 後台守護進程
  pidFilePath: /var/run/mongodb/mongod.pid  # location of pidfile
  timeZoneInfo: /usr/share/zoneinfo

# network interfaces
net:
  port: 27017
  bindIp:  0.0.0.0  # 綁定訪問IP,若為0.0.0.0則不限制地址


security:
  authorization: enabled  #啟用身份鑒別功能
#operationProfiling:

#replication:

#sharding:

## Enterprise-Only Options

auditLog:   #啟用資料庫審計功能,目前僅企業版支援
   destination: file    #配置審計日誌存儲類型,可為console、file、syslog
   format: BSON    #配置審計日誌格式,可以為JSON、BSON,若為BSON,則審計日誌需要藉助bsondump進行查看,如 bsondump  /var/log/auditlog.bson
   path: data/db/auditLog.bson   #審計日誌保存路徑
#snmp:

2. 啟用資料庫

a. mongod --config /etc/mongod.conf #通過配置文件啟用資料庫
b. mongod --dbpath data/db --auditDestination file --auditFormat BSON --auditPath data/db/auditLog.bson

通過添加參數啟用資料庫

3.登錄資料庫

a. 若配置了資料庫環境,則直接使用mongo登錄資料庫
b. 若未配置環境,則先進入資料庫目錄/bin下,使用./mongo登錄資料庫

二、資料庫的簡單使用

1. mongodb構成

mongodb資料庫由資料庫(database)、集合(collection)、文檔(document)組成。
其中一個mongodb實例可以創建多個資料庫。
一個資料庫可以創建多個集合(類似MySQL的表)。
一個集合由多個文檔構成(文檔相當於MySQL表裡的行,是資料庫的基本單元)。
一個文檔中可以存在多個欄位(相當於MySQL里的列)

2. mongodb的內建庫

admin庫:主要存放資料庫帳號的相關資訊。
local庫:local庫永遠不會被複制到從節點,可以用來存放僅限於本地管理的集合,副本配置資訊、oplog等。
config庫:用於分片集群環境,存放了分片相關的元數據資訊。
test庫:mongodb默認創建的測試庫,當連接資料庫時不指定對應的庫, 默認會連接到test庫。

拓展:Oplog 是用於存儲 MongoDB 資料庫所有數據的操作記錄的(實際只記錄增刪改和一些系統命令操作,查是不會記錄的),有點類似於 mysql 的 binlog 日誌。

3. 資料庫的簡單使用

3.1 創建資料庫

語法:use Database_name
#使用 use 加資料庫名稱,若資料庫存在,則切換到指定資料庫,若不存在,則創建該資料庫。

> use demo   #創建demo資料庫
switched to db demo
> show dbs    #查找所有資料庫
admin   0.000GB
config  0.000GB
local   0.000GB
> db.demo.insert({'name':'測試'})   #插入數據
WriteResult({ "nInserted" : 1 })
> show dbs
admin   0.000GB
config  0.000GB
demo    0.000GB
local   0.000GB
> show tables  #查看當前資料庫下的集合
demo

資料庫創建後,若不插入數據,默認是不顯示的,需要向資料庫中插入數據後才能顯示。

3.2 刪除資料庫

語法:db.dropDatabase()   #表示刪除當前資料庫

> db
demo
> db.dropDatabase()
{ "dropped" : "demo", "ok" : 1 }
> db
demo
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB

3.3 創建集合

語法:db.createCollection(name,options)
name:指定集合的名稱
options:可選參數,如下
欄位 類型 描述
capped 布爾 (可選)若為true,則創建固定大小的集合,當集合達到指定大小時,會自動覆蓋舊文檔,並需要配置size參數
size 數值 (可選)為固定集合指定一個最大值,即位元組數
max 數值 (可選)指定固定集合中文檔的最大數量
在插入文檔時,mongodb會先檢查固定集合的size欄位,再檢查max欄位;

> db.createCollection('mytest',{capped:true,size:2000,max:100})
{ "ok" : 1 }

3.4 刪除集合

語法:db.collection_name.drop()  #刪除指定的集合

> db     #顯示當前庫
demo
> show collections  #顯示資料庫下的集合,和show tables類似
demo
test
> db.test.drop()  #刪除集合
true
> show collections
demo
>

3.5 插入文檔

語法:db.collection_name.insert()  #若插入的數據主鍵已經存在,則會拋出org.springframework.dao.DuplicateKeyException 異常,提示主鍵重複,不保存當前數據。
或使用
db.COLLECTION_NAME.save(document)  #新版本已棄用,採用db.collection.insertOne()和db.collection.replaceOne()來替代。

> db.mytest.insert({'name':'黎明'})
WriteResult({ "nInserted" : 1 })
> db.mytest.find()
{ "_id" : ObjectId("609640173131453fc5ed5767"), "name" : "黎明" }

#只插入一個文檔
> db.mydemo.insertOne(
...    {
...       name: "sue",
...       age: 19,
...       status: "P"
...    }
... )
#返回值
{
        "acknowledged" : true,
        "insertedId" : ObjectId("6096429f3131453fc5ed5769")
}
> db.mydemo.find()
{ "_id" : ObjectId("6096429f3131453fc5ed5769"), "name" : "sue", "age" : 19, "status" : "P" }


#同時插入多個文檔
> db.mydemo.insertMany(
    [
        {name:'李一',age:1},
        {name:'李二',age:2},
        {name:'李三',age:3}
    ]
)
#以下為返回值
{
        "acknowledged" : true,
        "insertedIds" : [
                ObjectId("609643463131453fc5ed576a"),
                ObjectId("609643463131453fc5ed576b"),
                ObjectId("609643463131453fc5ed576c")
        ]
}
> db.mydemo.find()
{ "_id" : ObjectId("6096429f3131453fc5ed5769"), "name" : "sue", "age" : 19, "status" : "P" }
{ "_id" : ObjectId("609643463131453fc5ed576a"), "name" : "李一", "age" : 1 }
{ "_id" : ObjectId("609643463131453fc5ed576b"), "name" : "李二", "age" : 2 }
{ "_id" : ObjectId("609643463131453fc5ed576c"), "name" : "李三", "age" : 3 }

拓展-同樣能實現插入效果的方法

db.collection.update() 當upsert為true時//第三個參數  
db.collection.updateOne() 當upsert為true時//第三個參數 
db.collection.updateMany() 當upsert為true時//第三個參數
db.collection.findAndModify() 當upsert為true時  
db.collection.findAndModify() 當upsert為true時  
db.collection.findOneAndReplace() 當upsert為true時  
db.collection.bulkWrite()