insert: 插入資料
簡要說明
MongoDB中不支持庫和集合單獨的創建,也就是無法創建一個空的集合,
如果你進入的這個庫或是這個集合是一個新的,那么需要在里面添加資料才能進行保留,
一、基本使用
1、判斷資料庫是否存在
代碼如下:
# coding:utf8 import pymongo as p client = p.MongoClient("mongodb://localhost:27017") s1 = input("檢查資料庫是否存在,請輸入") if s1 in client.list_database_names(): print("資料庫已經存在") else: print("資料庫不存在,可以使用")
client.list_database_names() 列出當前連接中的所有資料庫,
2、判斷集合是否存在
代碼如下:檢查指定的集合是否在local庫里
# coding:utf8 import pymongo as p client = p.MongoClient("mongodb://localhost:27017") db = client["local"] s = input("請輸入檢查的集合名") if s in db.list_collection_names(): print("集合已經存在") else: print("集合不存在,可以使用")
db.list_collection_names()列出當前資料庫下所有的集合
3、插入單條資料
我們創建一個新的資料庫叫love,里面有一個集合users

代碼如下:
# coding:utf8 import pymongo as p # 鏈接資料庫 client = p.MongoClient("mongodb://localhost:27017") # 進入資料庫, 這個資料庫和集合其實不存在,我們進入它然后插入一條資料,它就存在了, mydb = client["love"] student = mydb["users"] # 插入的資料其實就是字典 dict1 = {"name": "白起", "age": 20, "height": 170} x = student.insert_one(dict1) # 列印插入資料的id、users集合 print(x.inserted_id) for v in student.find(): print(v)
運行結果:

4、插入多條資料
代碼如下:
# coding:utf8 import pymongo as p # 鏈接資料庫 client = p.MongoClient("mongodb://localhost:27017") # 進入資料庫, 這個資料庫和集合其實不存在,我們進入它然后插入一條資料,它就存在了, mydb = client["love"] student = mydb["users"] # 插入的資料其實就是字典 list1 = [{"name": "白起", "age": 21, "height": 170}, {"name": "王翦", "age": 22, "height": 170}, {"name": "李牧", "age": 23, "height": 170}, {"name": "廉頗", "age": 24, "height": 170}, {"name": "孫武", "age": 25, "height": 170}] # 插入多條資料 x = student.insert_many(list1) # 列印插入資料的id、users集合 print(x.inserted_ids) for v in student.find(): print(v)
運行結果:

5、插入的id是可以自定義的,不設定則系統會自動生成,
代碼如下:
# coding:utf8 import pymongo as p # 鏈接資料庫 client = p.MongoClient("mongodb://localhost:27017") # 進入資料庫, 這個資料庫和集合其實不存在,我們進入它然后插入一條資料,它就存在了, mydb = client["love"] student = mydb["users"] # 插入的資料其實就是字典 list1 = [{"_id": 1, "name": "白起", "age": 21, "height": 170}, {"_id": 2, "name": "王翦", "age": 22, "height": 170}, {"_id": 3, "name": "李牧", "age": 23, "height": 170}, {"_id": 4, "name": "廉頗", "age": 24, "height": 170}, {"_id": 5, "name": "孫武", "age": 25, "height": 170}] # 插入多條資料 x = student.insert_many(list1) # 列印插入資料的id、users集合 print(x.inserted_ids) for v in student.find(): print(v)
運行結果:

讀書和健身總有一個在路上
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/149352.html
標籤:Python
下一篇:MongoDB的delete
