Node.js 如何在MongoDB中使用facet计算百分比?

Node.js 如何在MongoDB中使用facet计算百分比?,node.js,mongodb,mongoose,aggregation-framework,Node.js,Mongodb,Mongoose,Aggregation Framework,我正在计算应用程序中的通知百分比,以便跟踪一些统计数据 我的收藏: [ { _id: "123", status: "seen", userId: "589" }, { _id: "223", status: "seen", userId: "589" }, { _id: "474"

我正在计算应用程序中的通知百分比,以便跟踪一些统计数据

我的收藏:

[
  {
    _id: "123",
    status: "seen",
    userId: "589"
  },
  {
    _id: "223",
    status: "seen",
    userId: "589"
  },
  {
    _id: "474",
    status: "unseen",
    userId: "589"
  },
  {
    _id: "875",
    status: "seen",
    userId: "112"
  },
  {
    _id: "891",
    status: "unseen",
    userId: "112"
  }
]
预期结果:

在这里我们可以看到,
UserId-589
已经收到了3个通知,其中2个被看到。因此,计算结果为
(totalNumOfSeen/totalNumOfNotificationsSent)*100

[{
    userId: "589",
    notificationPercentage : 66.66
},{
    userId: "112",
    notificationPercentage : 50
}]
我正在使用一个方面进行分组和匹配,但这将返回一个对象数组,我不知道如何对此执行除法

我的问题是:

db.collection.aggregate([
  {
    $facet: {
      totalNumOfSeen: [
        {
          $match: {
            userId: "589",
            status: "seen"
          }
        },
        {
          $group: {
            _id: "$userId",
            totalNumOfSeen: {
              $sum: 1
            }
          }
        }
      ],
      totalNumOfNoticationsSent: [
        {
          $match: {
            userId: "589",
            
          }
        },
        {
          $group: {
            _id: "$userId",
            totalNumOfNoticationsSent: {
              $sum: 1
            }
          }
        }
      ]
    }
  }
])
上面的查询给出了以下结果:

[
  {
    "totalNumOfNoticationsSent": [
      {
        "_id": "589",
        "totalNumOfNoticationsSent": 3
      }
    ],
    "totalNumOfSeen": [
      {
        "_id": "589",
        "totalNumOfSeen": 2
      }
    ]
  }
]
MongoPlayground-

现在我需要再添加一个字段作为
notificationPercentage
,并根据上述方面的结果计算通知百分比。非常感谢您的帮助。

您可以试试

  • $group
    根据
    用户ID
    并使用
    $cond
    获取
    totalSeen
    计数,如果
    状态
    seen
    ,则使用
    $sum
    获取通知的总计数
  • $project
    显示必填字段,并使用
    $divide
    $multiply
    计算百分比

db.collection.aggregate([
  {
    $group: {
      _id: "$userId",
      totalSeen: {
        $sum: { $cond: [{ $eq: ["$status", "seen"] }, 1, 0] }
      },
      total: { $sum: 1 }
    }
  },
  {
    $project: {
      _id: 0,
      userId: "$_id",
      notificationPercentage: {
        $multiply: [{ $divide: ["$totalSeen", "$total"] }, 100]
      }
    }
  }
])