什么是MongoDB?
MongoDB 是一個跨平臺的,面向檔案的資料庫,是當前 NoSQL 資料庫產品中最熱門的一種,它介于關系資料庫和非關系資料庫之間,是非關系資料庫當中功能最豐富,最像關系資料庫的產品,它支持的資料結構非常松散,是類似JSON 的 BSON 格式,因此可以存盤比較復雜的資料型別,其最小的單元是檔案,缺點:比較耗記憶體,
mongodb的庫、集合的操作
mongo:進入mongo
show dbs :查看所有資料庫 (前3個是配置資訊)
use 資料庫名 :切換/創建資料庫(存在就進入,不存在就創建)
db :查看所在庫
db.dropDatabase(): 洗掉庫(要先進入才能洗掉)
show collections :查看當前資料庫的集合
db.createCollection('stu') : 創建集合 stu:集合名
db.stu.drop() : 洗掉集合 stu:集合名
MongoDB的常用操作
1、增
db.集合名稱.insert(檔案)
示例:
#插入一條資料
db.stu.insert({name:'wang',age:19})
#插入多條資料
db.stu.insert([
{name:'wang',sex:'男',age:18},
{name:'li',sex:'女',age:16},
{name:'bai',sex:'男',age:19},
])
注意:我們插入資料后,系統會自動生成一個_id,我們可以在插入時更改這個id,如:
db.stu.insert({_id:1,name:'wang',age:19})
2、查
1、查詢所有資料
db.stu.find() 整體查詢
db.stu.find().pretty 格式化顯示,美觀查詢
2、條件查詢
db.stu.find({name:'wang'},{age:1}) 顯示滿足姓名為'wang'的年齡
db.stu.find({name:'wang'},{age:0}) 不顯示滿足姓名為'wang'的年齡
and條件、 or條件(注意在使用and或or前不能漏掉$)
db.students.find({$or:[{},{}]})
db.students.find({$or:[{$and:[{},{}]},{$and:[{},{}]}]})
$gt:大于
$lt:小于
$gte:大于或等于
$lte:小于或等于
$ne:不等于
示例:
db.stu.find({
$or:[
{$and:[{sex:'女'},{age:18}}]}, #條件1
{&and:[{sez:'男'},{age:{$gt:18}}]} #條件2
]
})
查詢滿足條件1或者條件2的資料
條件1:性別女并且年齡18歲
條件2:性別男并且年齡大于18歲
3、改
$set:有就修改,沒有就創建
db.stu.update({name:'wang'},{name:wangwang}) 只會修改一條資料,并且其他資料也沒了
db.stu.update({name:'wang'},{$set:{age:25}}) 只會修改一條資料,并且其他資料保留
db.stu.update({name:'bai'},{$set:{age:25}},{multi:true}) 會修改多條(所有滿足條件)資料,并且其他資料資料保留
4、刪
db.stu.remove({age:25},{justOne:true}) 只洗掉符合條件的第一條資料 注意justOne的大小寫
db.stu.remove({age:25}) 洗掉符合條件的所有資料
db.stu.remove({}) 洗掉所有資料
Python操作MongoDB
#準備--------------------------------------------------------
#匯入模塊
import pymongo
#systemctl start mongodb.service 開啟服務
#1、建立連接
client = pymongo.MongoClient('127.0.0.1',27017)
#2、指定資料庫
db = client['mydb']
#3、指定集合
collection = db['stu']
#操作---------------------------------------------------------
#增
#插入一條
collection.insert_one({'name':'wu','sex':'男','age':18})
#插入多條
collection.insert_many([
{'name':'wang','sex':'男','age':18},
{'name':'li','sex':'女','age':16},
{'name':'bai','sex':'男','age':19},
])
#改
#修改一條
collection.update_one({'name':'wang'},{'$set':{'age':20}})
#修改多條
collection.update_many({'name':'li'},{'$set':{'age':21}})
#刪
#洗掉一條滿足條件
collection.delete_one({'name':'li'})
#洗掉多條滿足條件
collection.delete_many({'name':'li'})
#洗掉所有
collection.delete_many({})
#查
data = collection.find()
for i in data:
print(i)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/280546.html
標籤:其他
下一篇:資料庫范式例題
