【问题标题】:How to count filtered results in $match in mongodb?如何在 mongodb 中计算 $match 中的过滤结果?
【发布时间】:2021-06-10 12:04:31
【问题描述】:

我有一个这样的聚合查询

nSkip=4, count=25, sortOn='first_name' , order=-1, toMatch='biker' // all variables are dynamic
query={status: true, roles: { $regex: toMatchRole, $options: "m" }} // also dynamic

User.aggregate([
      {
        $match: query
      }, 
      // after this I need the total number of documents that matched the criteria, 
      // before sorting or skipping or limiting in "total_count" variable
      {
        $sort: {
          [sortOn]: order
        }
      },
      {
        $skip: nSkip
      },
      {
        $limit: count
      },
      {
        $project: {
         last_name: 1,
         first_name: 1,
         email: 1
        }
      }
    ])

用户收藏

{
  _id:60befdcfa4198332b728f9cd",
  status:false,
  roles:["biker"],
  email:"john@textmercato.com",
  last_name:"aggr",
  first_name:"john",
}

我不确定如何在不干扰聚合的其他阶段的情况下实现这一目标。谁能帮帮我。

【问题讨论】:

    标签: node.js mongodb aggregation-framework


    【解决方案1】:

    你可以使用$group

    {
        "$group": {
          "_id": null,
          "data": { "$push": "$$ROOT" },
          "total_count": { $sum: 1 }
        }
        },
        { $unwind: "$data" },
        {
        "$replaceRoot": {
          "newRoot": {
            "$mergeObjects": [ "$$ROOT", "$data" ]
          }
        }
    }
    

    最后投影 total_count

    工作Mongo playground

    【讨论】:

    • 我们不需要 $match 阶段吗?
    • 你需要,但为了方便,我删除了它
    猜你喜欢
    • 2021-07-22
    • 1970-01-01
    • 2017-01-23
    • 2015-05-26
    • 2022-11-30
    • 1970-01-01
    • 2012-10-03
    • 2016-04-27
    • 1970-01-01
    相关资源
    最近更新 更多