2

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 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.