mongodb 집계에서 다른 문서의 항목 계산

Nov 17 2020

나는 두 개의 다른 문서를 가지고

Accounts
[
  {_id:1, name:'xyz'},
  {_id:2, name:'abc'},
  {_id:3, name:'def'},
  {_id:4, name:'pqr'},
]

Responses
[
  {_id:01, accountId:2, questionId: 0001, res: true},
  {_id:02, accountId:2, questionId: 0002, res: true},
  {_id:03, accountId:1, questionId: 0003, res: false},
  {_id:03, accountId:3, questionId: 0002, res: false},
  {_id:03, accountId:2, questionId: 0003, res: false},
]

원래 필드도 유지하면서 개별 계정에 대한 거짓 응답 의 수를 어떻게 계산할 수 있습니까 ?

예 :

{
  _id: 2,
  name: 'abc',
  trueResponses: 2,
  falseResponses: 1
}

$ lookup을 사용하여 필드의 다른 문서를 조인하려고 시도했지만 다른 응답을 계산할 수 없습니다.

db.accounts.aggregate([
    {
        $match: { _id: 2 }
    },
    {
        $lookup:{
            from: 'responses',
            localField: '_id',
            foreignField: 'accountId',
            as: 'responses'
        }
    }
])

답변

1 varman Nov 18 2020 at 03:36

여러 가지 방법이 있습니다.

  • $match 원치 않는 데이터 제거
  • $lookup 컬렉션에 참여하려면
  • $unwind 배열을 분해하려면
  • $group배열을 재구성하고 조건을 $sum사용하여 1 씩 증가시키는 데 도움이됩니다.$cond

다음은 스크립트입니다.

db.Accounts.aggregate([
  { $match: { _id: 2 } }, { $lookup: {
      from: "Responses",
      localField: "_id",
      foreignField: "accountId",
      as: "responses"
    }
  },
  {
    $unwind: "$responses"
  },
  {
    $group: { _id: "$_id",
      name: { $first: "$name" },
      trueResponses: {
        $sum: { $cond: [{ $eq: [ "$responses.res", true]},1,0]
        }
      },
      falseResponses: {
        $sum: { $cond: [{ $eq: [ "$responses.res", false]},1,0]
        }
      }
    }
  }
])

일하는 몽고 놀이터