Count items from another document in mongodb aggregation

徘徊边缘 提交于 2020-12-12 21:34:25

问题


I have two distinct documents as

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

and

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

How can I count number of true and false responses for an individual account while maintaining its original fields too.

Eg.

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

I have tried using $lookup to join the other document in a field but am unable to count different responses.

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

回答1:


There are many ways,

  • $match eliminate unwanted data
  • $lookup to join collections
  • $unwind to deconstruct the array
  • $group to reconstruct the array and $sum helps to increase by 1 using $cond condition

Here is the script

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

Working Mongo playground



来源:https://stackoverflow.com/questions/64883114/count-items-from-another-document-in-mongodb-aggregation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!