【问题标题】:Count items from another document in mongodb aggregation在 mongodb 聚合中计算另一个文档中的项目
【发布时间】:2021-03-01 03:11:29
【问题描述】:

我有两个不同的文档

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

我如何计算单个帐户的 truefalse 响应数,同时保留其原始字段。

例如。

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

我尝试使用 $lookup 将另一个文档加入某个字段,但无法计算不同的响应。

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

【问题讨论】:

    标签: mongodb mongoose aggregation-framework


    【解决方案1】:

    有很多方法,

    • $match 消除不需要的数据
    • $lookup加入收藏
    • $unwind 解构数组
    • $group 重建数组,$sum 使用 $cond 条件帮助增加 1

    这是脚本

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

    工作Mongo playground

    【讨论】:

      猜你喜欢
      • 2020-07-15
      • 2023-03-17
      • 2019-02-16
      • 1970-01-01
      • 1970-01-01
      • 2021-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多