管道
管道在Unix和Linux中一般用于將當(dāng)前命令的輸出結(jié)果作為下一個命令的參數(shù)耳奕,MongoDB的聚合管道將MongoDB文檔在一個管道處理完畢后將結(jié)果傳遞給下一個管道處理帜篇。管道操作是可以重復(fù)的。
管道操作符
常用管道 | 解析 |
---|---|
$group | 將collection中的document分組套耕,可用于統(tǒng)計結(jié)果 |
$match | 過濾數(shù)據(jù)规婆,只輸出符合結(jié)果的文檔 |
$project | 修改輸入文檔的結(jié)構(gòu)(例如重命名隘谣,增加、刪除字段破婆,創(chuàng)建結(jié)算結(jié)果等) |
$sort | 將結(jié)果進行排序后輸出 |
$limit | 限制管道輸出的結(jié)果個數(shù) |
$skip | 跳過制定數(shù)量的結(jié)果涮总,并且返回剩下的結(jié)果 |
$unwind | 將數(shù)組類型的字段進行拆分 |
表達式操作符
常用表達式 | 含義 |
---|---|
$sum | 計算總和,{ |
$avg | 求平均值 |
$min | 求min值 |
$max | 求max值 |
$push | 將結(jié)果文檔中插入值到一個數(shù)組中 |
$first | 根據(jù)文檔的排序獲取第一個文檔數(shù)據(jù) |
$last | 同理祷舀,獲取最后一個數(shù)據(jù) |
為了便于理解瀑梗,將常見的mongo的聚合操作和MySql的查詢做類比:
MongoDB聚合操作 | MySql操作/函數(shù) |
---|---|
$match | where |
$group | group by |
$match | having |
$project | select |
$sort | order by |
$limit | limit |
$sum | sum() |
$lookup | join |
Aggregation Pipeline 優(yōu)化
- 聚合管道可以確定它是否僅需要文檔中的字段的子集來獲得結(jié)果。 如果是這樣裳扯,管道將只使用那些必需的字段抛丽,減少通過管道的數(shù)據(jù)量
- 管道序列優(yōu)化化
map-reduce
image.png
單用途集聚操作
參考資料:
MongoDB系列--深入理解MongoDB聚合(Aggregation )
數(shù)據(jù)驗證
- JSON模式進行模式驗證
db.createCollection("students", {
validator: {
$jsonSchema: {
bsonType: "object",
required: [ "name", "year", "major", "address" ],
properties: {
name: {
bsonType: "string",
description: "must be a string and is required"
},
year: {
bsonType: "int",
minimum: 2017,
maximum: 3017,
description: "must be an integer in [ 2017, 3017 ] and is required"
},
major: {
enum: [ "Math", "English", "Computer Science", "History", null ],
description: "can only be one of the enum values and is required"
},
gpa: {
bsonType: [ "double" ],
description: "must be a double if the field exists"
},
address: {
bsonType: "object",
required: [ "city" ],
properties: {
street: {
bsonType: "string",
description: "must be a string if the field exists"
},
city: {
bsonType: "string",
"description": "must be a string and is required"
}
}
}
}
}
}
})
- 其他查詢表達式
db.createCollection( "contacts",
{ validator: { $or:
[
{ phone: { $type: "string" } },
{ email: { $regex: /@mongodb\.com$/ } },
{ status: { $in: [ "Unknown", "Incomplete" ] } }
]
}
} )