MongoDB資料庫簡筆

2021-10-09 06:59:17 字數 3036 閱讀 8770

mongodb是乙個面向文件儲存的非關係型資料庫,是用c++編寫的。

mongodb將資料儲存為乙個文件,資料結構由「鍵值對」組成,字段值

可以包含其他文件、陣列及文件陣列,類似於json物件,如下格式:

mongodb與sql對應的術語:

sqlmongodb

術語英文術語

術語英文術語

資料庫database

資料庫database

表table

集合collection

行row

文件document

列column

域field

索引index

索引index

主鍵primary key

主鍵primary key

pip install pymongo
import pymongo

# 方式一:使用預設的host和port

db_client = pymongo.mongoclient(

)# 方式二:自定義host和port引數

db_client = pymongo.mongoclient(host=

"localhost"

, port=

27017

)# 方式三:使用標準的uri連線語法

db_client = pymongo.mongoclient(

"mongodb://localhost:27017"

)

mongodb可以建立多個資料庫,以下**指定了名稱為qidian的資料庫:

db = db_client[

"qidian"

]

db = db_client.qidian
以下**指定了要操作的集合為hot:

db_collection = db[

'hot'

]

(1)插入與條件匹配的單個文件
novel =

result = db_collection.insert_one(novel)

print

(result)

# insertoneresult型別物件

print

(result.inserted_id)

# 新增文件的_id值,作為文件的唯一標識

(2) 插入與條件匹配的所有文件
novel1 =

novel2 =

result = db_collection.insert_many(

[novel1, novel2]

)print

(result)

(1) 查詢與條件匹配的單個文件
result = db_collection.find_one(

)

相當於

select

*from hot where name =

"帝國的崛起"

limit0,

1

(2) 查詢所有文件
cursor = db_collection.find(

)

相當於

select

*from hot;

(3) 查詢與條件匹配的所有文件
cursor = db_collection.find(

)print

(cursor)

for one in cursor:

print

(one)

相當於

select

*from hot where

type

="歷史"

(1) 更新與條件匹配的單個文件
# 查詢條件

filter

=# 更新語句

update =

}# 使用update_one()方法更新文件

result = db_collection.update_one(

filter

, update)

print

(result)

# 返回updateresult型別的物件

print

(result.raw_result)

# 檢視更新後的結果

filter是乙個查詢條件的字典,update是乙個更新語句的字典,key為操作符$set,value為想要更新的字段,也是乙個字典。

(2) 更新與條件匹配的所有文件

# 查詢條件

filter

=# 更新語句

update =

}# 使用update_many()方法更新文件

result = db_collection.update_many(

filter

, update)

print

(result)

# 返回updateresult型別的物件

print

(result.raw_result)

# 檢視更新後的結果

(1) 刪除與條件匹配的單個文件
result = db_collection.delete_one(

)print

(result)

print

(result.raw_result)

(2) 刪除與條件匹配的所有文件
result = db_connection.delete_many(

)print

(result)

print

(result.raw_result)

db_client.close(

)

公網訪問阿里雲資料庫MongoDB 填坑筆記

兩台伺服器,一台阿里雲ecs雲伺服器 專用網路 另一台是阿里雲資料庫mongodb,處於安全考慮mongodb是不執行外網連線的,那接下來就看怎麼實現公網訪問。專用網路和經典網路的大致區別可以用一句話講明白 專用網路更安全,需要設定和配置的東西比較多,適合精通網路的高手 經典網路使用更方便,適合更適...

MongoDB 資料庫操作

1 插入記錄 使用資料庫 如果沒有該資料庫就會建立,有就進入該模式 use use my testdb 插入資料 db.user.insert db.user.insert 顯示資料庫 show dbs my mongodb是隱式建立的資料庫 顯示表 show collections user是隱式...

MongoDB 建立資料庫

mongodb 建立資料庫的語法格式如下 use database name如果資料庫不存在,則建立資料庫,否則切換到指定資料庫。以下例項我們建立了資料庫 runoob use runoob switched to db runoob db runoob 如果你想檢視所有資料庫,可以使用 show ...