首页 > 解决方案 > mongodb匹配和组2查询合二为一

问题描述

var oneWeekAgo = new Date();
oneWeekAgo.setDate(oneWeekAgo.getDate() - 7);  



  User.aggregate([
            { $match: { isAdmin: false, isActive: true } },
            {
                $group: {
                    _id: null,
                    totalCount: {
                        $sum: 1
                    }
                }
            },
        ])


  User.aggregate([
                { $match: { isAdmin: false, dateCreated: { $gte: oneWeekAgo }, isActive: true } },
                {
                    $group: {
                        _id: null,
                        lastWeekTotal: {
                            $sum: 1
                        }
                    }
                },
            ])

有没有办法结合上面的 2 个聚合查询?

我想计算集合中的所有条目以及一周内创建的条目。预期结果:

[ { _id: null, totalCount: 100 , lastWeekTotal: 10 } ] 

标签: node.jsmongodbmongoose

解决方案


你可以$group像这样在里面组合在一起,

  • $cond运算符,有三个参数($cond: [if check condition, then, else])
  • 第一部分 if 条件使用 $and 运算符检查您的条件,如果条件为真则返回1否则0
User.aggregate([
  {
    $group: {
      _id: null,
      totalCount: {
        $sum: {
          $cond: [
            {
              $and: [
                { $eq: ["$isAdmin", false] },
                { $eq: ["$isActive", true] }
              ]
            },
            1,
            0
          ]
        }
      },
      lastWeekTotal: {
        $sum: {
          $cond: [
            {
              $and: [
                { $gte: ["$dateCreated", oneWeekAgo] },
                { $eq: ["$isAdmin", false] },
                { $eq: ["$isActive", true] }
              ]
            },
            1,
            0
          ]
        }
      }
    }
  }
])

操场


推荐阅读