Database/NoSQL

[MongoDB] 데이터 파이프라인과 Lookup

lumination 2025. 6. 16. 19:11

집계 함수

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
    }
  }
]