提问者:小点点

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

共1个答案

匿名用户

您可以像这样将$group内部组合在一起,

  • $cond运算符,有三个参数($cond:[if check condition,then,else])
  • 第一部分if condition使用$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
          ]
        }
      }
    }
  }
])

操场