一. 增刪查改
1. 增
(1.創建、連接數據庫
use <database>
(2. 創建集合
db.createCollection("<collectionname>")
db.createCollection("<collectionname>",
{capped=true,autoIndexId=true,size=1024,max=100}
)
注:
capped #創建固定大小的集
autoIndexId #自動在_id字段創建索引
size #固定集合大小
max #最大文件數
(3. 創建文檔(集合不存在自動創建)
db.<collection>.insertOne(
{ item: "canvas",
qty: 100,
tags: ["cotton"],
size: { h: 28, w: 35.5, uom: "cm" }
}
) #tags是數組,size是文檔
db.<collection>.insertMany(
{ item: "journal", qty: 25, tags: ["blank", "red"], size: { h: 14, w: 21, uom: "cm" } },
{ item: "mat", qty: 85, tags: ["gray"], size: { h: 27.9, w: 35.5, uom: "cm" } },
{ item: "mousepad", qty: 25, tags: ["gel", "blue"], size: { h: 19, w: 22.85, uom: "cm" } })
db.collection.insert()#單一的,多元的都可以。
db.collection.save()
2.刪
(1.刪除數據庫
db.dropDatabase() #刪除當前數據庫
(2. 刪除集合
db.<collection>.drop() #刪除指定數據庫的所有集合
(3.刪除文檔
db.collection.deleteMany({ <field1>: <value1>, ... })
db.collection.deleteOne({ <field1>: { <operator1>: <value1> }, ... })
db.collection.remove()
3.查
db.collection.find({<query},{<projection>})
({ <field1>: <value1>, ... })
({ <array field>: { <operator1>: <value1>, ... } })
({"size.uom"="in"}) #嵌套字段使用點表示法
({ <field1>:{ <field1.1>:<value1.1>, ... }})#數組中嵌套了文檔的查詢
注:
query #查詢條件
prohection #投影,表示哪些字段可以顯示
AND = ,
OR = $or: [ , ]
$lt: < (less than )
$lte: <= (less than or equal to )
$gt: > (greater than)
$gte: >= (greater than or equal to)
$ne: !=
$all: 當且僅當
$elemMatch 可將一組條件限定到數組中單條文檔的匹配上
4.改
db.collection.updateOne({<filter>}, {<update>}, <options>)
db.collection.updateMany({<filter>}, {<update>}, <options>)
db.collection.replaceOne({<filter>}, {<update>}, <options>)
filter #查詢條件
update #替換對象以及替換的值
例如
db.inventory.updateOne(
{ item: "paper" }, #查詢條件
{
$set: { "size.uom": "cm", status: "P" }, #修改對象以及替換的值
$currentDate: { lastModified: true } #
}
)
注:
$set:= $addFields: 向文檔添加新字段。如果存在則被替換
$currentDate: 字段更新時間爲當前日期,用來看啥時候給你更新的
$unset: 向文檔中刪除新字段
$addToSet:Adds elements to an array only if they do not already exist in the set.
$pop:Removes the first or last item of an array.
$pull:Removes all array elements that match a specified query.
$push:Adds an item to an array.
$:充當更新查詢文檔的第一個匹配項的佔位符。
二.聚合+mapReduce
1.聚合
MongoDB中聚合(aggregate)主要用於處理數據(諸如統計平均值,求和等),並返回計算後的數據結果。聚合操作將多個文檔的值分組在一起,並可以對分組數據執行各種操作以返回單個結果。
db.<collection>.aggregate()
注:
$match:# 按字段篩選文檔,並將等於的文檔傳遞到下一階段。
$group: #按字段對文檔進行分組,以計算每個唯一的量總和
2.mapReduce
參考文檔地址:https://docs.mongodb.com/manual/reference/operator/update/positional/(強烈推薦)
本文還有很多沒有陳列出來,沒有什麼比官方文檔更加詳細的了,而且文檔還給了我們shell來運行,太方便了。