공부 흔적남기기

Mongodb lookup 최적화 본문

데이터베이스/MongoDB

Mongodb lookup 최적화

65살까지 코딩 2024. 10. 21. 22:41
728x90
반응형
  1. localField와 foreignField를 사용
  • foreignField에 index를 생성해서 사용
  • pipeline을 통해서 match를 걸어 사용할 경우 $expr을 사용해야하기 때문에
  • 인덱스가 사용되지 않는다.
  1. from collection에서 가져올 데이터가 적다면
  • pipeline에 $project를 사용하고 해당 데이터들에 대해 인덱스를 생성해서 사용
  • 이런 방식으로 사용하면 collection을 읽지않고 covering Index를 사용해서 데이터를 가져오기 때문에 효과적인 $lookup 사용이 가능하다.

Good Example

Boards collection 에 userId와 userName에 index가 각각 걸려있음
coveringIndex를 사용하기 때문에 explain 해보면
"totalDocsExamined": 0 통해 알 수 있음
{
  from: "Boards",
  localField: "userId",
  foreignField: "userId",
  pipeline: [
    {
      $project: {
        userName : 1
      }
    }
    
  ],
  as: "result"
}

Bad Example

expr 때문에 agentId index를 사용하지못해 table full scan
{
  from: "Boards",
  let: {userId: "$userId"}
  pipeline: [
    {$match: {$expr: {$eq: ["$userId", "$$userId"]}  },
    {
      $project: {
        userName : 1
      }
    }
    
  ],
  as: "result"
}
728x90
반응형