繁体   English   中英

mongoose mongodb nodejs中的聚合查询

[英]aggregate query in mongoose mongodb nodejs

嗨,我正在我的 nodejs 代码中尝试以下查询

const totalCount = await model.countDocuments({
    'createdAt': { $gte: new Date(startDate), $lte: new Date(endDate) },
}).exec();

const activeCount = await model.countDocuments({
    'createdAt': { $gte: new Date(startDate), $lte: new Date(endDate) },
    'enabled': true,
}).exec();

const inactiveCount = (totalCount - activeCount);

return { totalCount, activeCount, inactiveCount };

有什么方法可以使用 mongoose 中的聚合将上述内容组合到单个查询中? 请指导我找到最佳解决方案。

是的,使用一些基本运算符非常简单,如下所示:

model.aggregate([
  {
    $match: {
      createdAt: {
        $gte: new Date(startDate),
        $lte: new Date(endDate)
      }
    }
  },
  {
    $group: {
      _id: null,
      totalCount: {
        $sum: 1
      },
      activeCount: {
        $sum: {
          $cond: [
            {
              $eq: [
                "$enabled",
                true
              ]
            },
            1,
            0
          ]
        }
      }
    }
  },
  {
    $project: {
      _id: 0,
      totalCount: 1,
      activeCount: 1,
      inactiveCount: {
        $subtract: [
          "$totalCount",
          "$activeCount"
        ]
      }
    }
  }
])

蒙戈游乐场

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM