집계 함수
GROUP BY, SUM , AVG, COUNT
$group, $sum, $avg, $count
-------
$lookup
$match
SELECT, AS
$project, $addFields, $set
------
[
{$match : {status : "A"}},
{$group : {"_id" : "$cust_id", total : {$sum : "$amount"}},
{$sort : {"total" : -1}
]
{
"cust_id" : "A",
"amount" : 3
}
{
"cust_id" : "B",
"amount" : 10
}
{
"cust_id" : "A",
"amount" : 3
}
{
"_id" : "A",
"total" : 6
}
{
"_id" : "B",
"total" : 10
}
Join과 동일한 Lookup
SELECT c.name, o.amount
FROM customers c
JOIN orders o ON c.cust_id = o.customer_id
db.customers.aggregate([
{
$lookup: {
from: "orders",
localField: "cust_id",
foreignField: "customer_id",
as: "orders"
}
},
{ $unwind: "$orders" }, #unwind까지 하면 orders는 오브젝트 형태로 변경
{ $project: { name: 1, "orders.amount": 1 } }
])
[
{
$lookup: {
from: "orders",
let: { customerId: "$cust_id" },
pipeline: [
{ $match: { $expr: { $eq: ["$customer_id", "$$customerId"] } } }
// 필요 시 추가 조건 삽입
],
as: "orders"
}
},
{
$unwind: {
path: "$orders",
preserveNullAndEmptyArrays: false
}
}
]
'Database > NoSQL' 카테고리의 다른 글
[MongoDB] 실전 쿼리 작성2 (0) | 2025.06.17 |
---|---|
[MongoDB] 실전 쿼리 작성 (0) | 2025.06.16 |
[MongoDB] Cursor (0) | 2025.06.16 |
[MongoDB] 정렬과 페이징 (0) | 2025.06.16 |
[MongoDB] 주요 쿼리 연산자 (0) | 2025.06.16 |