---
# System prepended metadata

title: Mongo 資料庫簡易上手
tags: [程式學習與問題總集, 人生苦短，我學Python]

---

# Mongo 資料庫簡易上手
###### tags: `程式學習與問題總集`
###### tags: `人生苦短，我學Python`

## 1. 註冊及登入[mongo database](https://www.mongodb.com/cloud/atlas/lp/try2?utm_source=google&utm_campaign=gs_apac_taiwan_search_core_brand_atlas_desktop&utm_term=mongodb&utm_medium=cpc_paid_search&utm_ad=e&utm_ad_campaign_id=12212624371&gclid=CjwKCAjwuvmHBhAxEiwAWAYj-AVVh-3EfotgpGm7rwWFGQzmQns8arpxsMCzlIupDPn-AM3tX3599xoCYCMQAvD_BwE)

## 2. Altas [點這邊](https://www.mongodb.com/cloud/atlas/efficiency?utm_source=google&utm_campaign=gs_apac_taiwan_search_core_brand_atlas_desktop&utm_term=mongodb&utm_medium=cpc_paid_search&utm_ad=e&utm_ad_campaign_id=12212624371&gclid=CjwKCAjwuvmHBhAxEiwAWAYj-BaTOKVzZIIcnS-k2vulVcUU7WUSXjz9MF0tpuZiMTzfnB1lwMB73RoCxtMQAvD_BwE)

----------------------
* 之後應該會出現這個畫面
![](https://i.imgur.com/r1hqZqA.png)
* 點擊Add new project
![](https://i.imgur.com/5zQL7Ns.png)
* next後，create the Project

* 創建資料庫
![](https://i.imgur.com/baw9fWW.png)

* 選免錢的
![](https://i.imgur.com/LbVyWXR.png)

* create
![](https://i.imgur.com/IV4VqUU.png)

* 點擊Database Access
![](https://i.imgur.com/oNAdYTK.png)

* 自己設定密碼
![](https://i.imgur.com/oyGX75q.png)

* 點擊Network Access，Add an IP address(右邊的按下去)
 ![](https://i.imgur.com/wHGGMfU.png)

* 回到Database，點擊Browse Collection、Add My Own Data
![](https://i.imgur.com/cq909fO.png)

* 回到Database，點擊Connect
![](https://i.imgur.com/De7ss92.png)

* 點中間的
![](https://i.imgur.com/AtusS73.png)

* 複製程式碼
```python=
#這是範例
mongodb+srv://admin:<password>@cluster0.ltujo.mongodb.net/myFirstDatabase?retryWrites=true&w=majority
```

## 新增資料
* 打開資料夾，先嘗試使用這個資料庫，隨便建立一個檔案

```python=
pip install mongo
```

```python=
import pymongo
from pymongo import MongoClient

cluster = MongoClient("剛剛複製的，password換成自己的就好")

db = cluster['discord_bot_database']
collection = db['data']

post = { "name" : "12345"}

collection.insert_one(post)
```
* 執行後
![](https://i.imgur.com/8ACzczN.png)

## 查詢資料

* 找到第一個key值 = 12345
```python=
import pymongo
from pymongo import MongoClient

cluster = MongoClient("剛剛複製的")

db = cluster['discord_bot_database']
collection = db['data']

findone = collection.find_one({'name' : '12345'})

print(findone)
```
* 執行後
![](https://i.imgur.com/qiLaCn6.png)

## 修改資料
* 修改第一個name值
```python=
import pymongo
from pymongo import MongoClient

cluster = MongoClient("剛剛複製的")

db = cluster['discord_bot_database']
collection = db['data']

first_data = {'name':"12345"}

second_data = {"$set" : {"name":"50000"}}

collection.update_one(first_data, second_data)
print("Successful")
```

* 結果
![](https://i.imgur.com/3GmhVkG.png)

## 刪除資料
* 刪除第一個name
```python=
import pymongo
from pymongo import MongoClient

cluster = MongoClient("剛剛複製的")

db = cluster['discord_bot_database']
collection = db['data']

del_data = {"name":"50000"}

collection.delete_one(del_data)

print("Successful")
```
* 結果
![](https://i.imgur.com/1ogkXGa.png)


{%hackmd S1DMFioCO %}