---
# System prepended metadata

title: Mongo Db 操作筆記
tags: [Database]

---

---
title: Mongo Db 操作筆記
---
# Mongo Db 操作筆記
###### tags: `Database`

### 安裝
1. 安裝：執行 docker-compose up -d
```
version: "3"

services:
  db:
    image: mongo
    container_name: mongo
    volumes:
      - ./database:/data
    ports:
      - "27018:27017"
    environment:
      MONGO_INITDB_ROOT_USERNAME: admin
      MONGO_INITDB_ROOT_PASSWORD: admin
```
2. 進入container, usr/bin, 執行mondo
3. 權限認證
```
use admin
db.auth('admin','admin')
```
4. 此時測試show dbs，有回應及正常
```
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
```
5. 新增db 
```
use newDB
```
(此時show users 是空)

6. 新建newDB user 
```
db.createUser({user:"dev",pwd:"123456",roles:["dbAdmin"]}) 
```
dbAdmin角色 只能在該db內執行相關操作

7. 增加使用者授權
```
db.grantRolesToUser('devB', [{ role: 'readWrite', db: 'newDB' }]);
```

### 基礎指令
1. 建立collection：db.createCollection('users')
2. 查詢collection: show collections
3. 新增：db.users.insert({"name":"ghost", "age":10})  
4. 查詢：db.users.find()
5. 刪除by id : db.users.deleteOne({"_id":ObjectId("624995a5bbce277fb8fea107")})



角色參考:https://www.mongodb.com/docs/manual/reference/built-in-roles/#mongodb-authrole-dbAdmin
操作範例:https://blog.hackajob.co/crud-transactions-in-mongodb-with-go/
Golang 程式碼:https://github.com/ronnielin8862/go-practice/blob/master/cmd/db/mangoDb/main.go