【问题标题】:How to get grouped data as well as all data using mongodb?如何使用 mongodb 获取分组数据以及所有数据?
【发布时间】:2021-07-28 14:58:55
【问题描述】:

使用以下代码,我得到了 totalAccount 和 totalBalance。但是,没有其他字段/数据出现。如何从我的集合中获取与我的查询匹配的所有数据(brcode)?

const test = await db.collection('alldeposit').aggregate([
        {
            $match: {
                brcode: brcode
               
            }
        },
        
        {
           $group: {
               _id: null,
               totalAccount: {
                   $sum: 1
               },
               totalBalance: {
                   $sum: "$acbal"
               }
           }
        }
        
    ]).toArray()

【问题讨论】:

    标签: javascript node.js mongodb mongodb-query aggregation-framework


    【解决方案1】:

    你必须指定你想在$group阶段看到哪些字段

    例如:

        await db.collection('alldeposit').aggregate([
           {
               $match: {
                   brcode: brcode
               }
           },
          {
          $group: {
             _id : null,
             name : { $first: '$name' },
             age : { $first: '$age' },
             sex : { $first: '$sex' },
             province : { $first: '$province' },
             city : { $first: '$city' },
             area : { $first: '$area' },
             address : { $first: '$address' },
             totalAccount: {
                 $sum: 1
             },
             totalBalance: {
                $sum: "$acbal"
             }
          }
        }]);
    

    编辑:

    关于我们在 cmets 中的聊天,很遗憾,我不知道如何在单个聚合中执行您要求的操作。

    但只需两步,你就可以做到:

    第一步:

    db.collection.aggregate([
      {
          $match: {
             brcode: brcode
          }
      },
      {
        "$group": {
          "_id": null,
          totalAccount: {
            $sum: 1
          },
          totalBalance: {
            $sum: "$acbal"
          }
        }
      }
    ])
    

    第二步:

    db.collection.update(
      { brcode: brcode }
      ,{$set : {
         "totalAccount": totalAccount,
         "totalBalance": totalBalance
       }}
    )
    

    【讨论】:

    • 谢谢。我试过你的代码。它只显示一个记录。但是,我有数百条记录。如何从我的收藏中获取所有记录?
    • $group 背后的逻辑是在单个文档中显示分组数据。如果您想在结果中显示所有内容,则必须使用$project 舞台而不是$group 如果您需要帮助,我可以在我的答案中举一个例子。
    • 因为我已经在数组 [{ }] 中有 totalAccount 和 totalBalance,对于所有其他记录,如果我能以这种方式获取所有记录,那就太好了 => [{totalAccount 和 totalBalance} , {所有其他数据来自集合}]
    • 是的,项目是一个选项。但是,是否可以使用单个 mongodb 聚合(或任何其他方式)从集合中获取 totalAccount、totalBalance 以及所有数据?
    • 好的,知道了。有时间我会更新我的答案。
    猜你喜欢
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-14
    • 1970-01-01
    • 2021-07-09
    • 2018-11-10
    • 1970-01-01
    相关资源
    最近更新 更多