Mongodb學習總結

2020/4/2
Mongodb使用的是類似與json字元串的形式存儲數據
[
{
key:value
},
{
key:value
},
]

Mongodb使用了不存在的對象,即創建該對象

use db 使用db資料庫
show dbs 查看當前伺服器中寫在磁碟上的資料庫
show tables 查看資料庫中的collection
db 查看當前使用的資料庫

1.增刪改查:
增:
db.collection.insert({數據}) 自動生成 _id : ObjectId("")
官方推薦:
db.collection.insertOne({數據}) 插入一條數據
db.collection.insertMany([{數據},{數據}]) 插入多條數據
查:
db.collection.find({條件})
db.collection.findOne({條件})
改:
db.collection.update({條件},{$修改器:{數據}})
官方推薦:
db.collection.updateOne({條件},{$修改器:{數據}}) 更新一條數據
db.collection.updateMany({條件},{$修改器:{數據}}) 更新所有數據
刪:
db.collection.remove({條件})
官方推薦:
db.collection.deleteOne({條件}) 刪除一條數據
db.collection.deleteMany({條件}) 刪除所有符合條件的數據

清除collection:
db.collection.drop()

2.$關鍵字
數學比較符:
$lt
$lte
$gt
$gte
$eq :
db.collection.find("score":{$gt:80})
查詢關鍵字:
$or db.collection.find({$or:[{name:1},{age:73}]})
$in db.collection.find({age:{$in:[1,2,3,4]}}) #符合其中一個條件即可
$all db.collection.find({hobby:{$all:[1,2,3,4]}}) #子集查詢

2018年12月25日:
1.$修改器 :
$set 簡單粗暴 {name:value} dict["name"]=value

$unset 簡單粗暴的刪除欄位 {$unset:{name:1}} del dict["name"]  db.user_info.updateOne({age:200},{$unset:{age:1}})    $inc 引用增加  db.user_info.updateMany({},{$inc:{age:1}})    array操作  $push 在array中追加一個新的元素 [].append(item)  db.user_info.updateOne({name:"200wansui"},{$push:{hobby:10}})    $pull 在array中刪除一個的元素 [].remove(item) [].pop(-1)  db.user_info.updateOne({name:"200wansui"},{$pull:{hobby:0}})    $pop 不含索引 -1 從前往後  1 從後往前  db.user_info.updateOne({name:"200wansui"},{$pop:{hobby:1}})  

2.$ 字元
db.user_info.updateOne({hobby:6},{$set:{"hobby.$":"六"}})
保存符合索引條件數據的下標

3.Object 字典操作
db.user_info.updateOne({name:"200wansui"},{$inc:{"info.tizhong":-5}})
db.user_info.updateOne({name:"200wansui"},{$set:{"info.long":12.5}})

4.array + Object
db.user_info.updateOne({"hobby.shengao":150},{$set:{"hobby.$.long":14}})

5.limit
db.user_info.find({}).limit(5)
選取數據從當前位置選擇5個

6.skip 跳過
db.user_info.find({}).skip(2)
從0開始跳過2條數據為當前位置

7.sort
db.user_info.find({}).sort({ id:-1 })
根據ID進行排序 -1倒敘 1正序

8.limit+skip+sort
db.user_info.find({}).limit(5).skip(10)
db.user_info.find({}).limit(c).skip((p-1)*c)

db.user_info.find({}).limit(5).skip(5).sort({ id:-1 })    優先順序最高的是 sort  其次優先為 skip  最低優先順序 limit  

9.pymongo