Aggregate
- 在 MongoDB 中屬於重量級工具
- pipeline 管道模型理論:后面操作的數據源來源於上一次操作的結果
- pipeline aggregate stages
$project // 指定獲取字段
$match // 篩選
$redact
$limit
$skip
$unwind
$group
$sample
$sort
$geoNear
$lookup // 關聯
$out
$indexStats
$lookup 關聯表
product 表:
| _id | productname | price |
|---|---|---|
| 1.0 | 商品1 | 15.0 |
| 2.0 | 商品2 | 36.0 |
orders 表:
| _id | pid | ordername |
|---|---|---|
| 1.0 | 1.0 | 訂單1 |
| 2.0 | 2.0 | 訂單2 |
| 3.0 | 3.0 | 訂單3 |
| 4.0 | 4.0 | 訂單4 |
db.product.aggregate([
{
$lookup:
{
from: "orders", // 需要關聯的表
localField: "_id", // product 表需要關聯的鍵
foreignField: "pid", // orders 的 matching key
as: "inventory_docs" // 對應的外鍵集合的數據
}
}
])
$match 篩選數據
// 篩選出價格 大於 20 的商品
db.product.aggregate([
{
$lookup: {
from: "orders", // 需要關聯的表
localField: "_id", // product 表需要關聯的鍵
foreignField: "pid", // orders 的 matching key
as: "inventory_docs" // 對應的外鍵集合的數據
}
},
{
$match: {
price: { $gt:20 }
}
}
])
$project 指定獲取字段
// 價格大於 20 的訂單
db.product.aggregate([
{
$lookup: {
from: "orders", // 需要關聯的表
localField: "_id", // product 表需要關聯的鍵
foreignField: "pid", // orders 的 matching key
as: "inventory_docs" // 對應的外鍵集合的數據
}
},
{
$match: {
price: { $gt:20 }
}
},
{
$project:{
"inventory_docs": 1,
"_id": 0
}
}
])
