【问题标题】:Mongoose aggregate if _id match如果 _id 匹配,则 Mongoose 聚合
【发布时间】:2020-07-14 20:51:59
【问题描述】:

我有一个查询,在视频模型中找到,它获取视图,但我需要根据 userId 的视图,例如 userId="1xxxxxxxxx13", 有可能吗?

Video.aggregate(
    [
      {
        $group: {
          _id: null,
          totalViews: {
            $sum: {
              $cond: [{ $eq: ["$userId", id] }, "$views", 0],
            },
          },
        },
      },
    ],
    function (err, data) {
      console.log(data);
      return data;
    }
  );

quer,给我零次观看,但有来自 tht userId 的视频观看次数 这是架构

const mongoose = require("mongoose");

const videoSchema = new mongoose.Schema({
  ....
  thumbnail: { type: String, required: false },
  title: { type: String, required: false },
  userId: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
  views: { type: Number },
  ....
  
});
videoSchema.index({ title: "text" });
module.exports = mongoose.model("Video", videoSchema);

我需要过滤特定用户的视频

【问题讨论】:

    标签: node.js mongodb mongoose mongodb-query aggregation-framework


    【解决方案1】:

    看起来您正在计算每个用户的观看次数。

    您可以执行以下操作。按用户 ID 分组并计算视图。它返回用户明智的 viewCounts

     [
          {
            $group: {
              _id: $userId,
              totalViews: {
                $sum: "$views",
              }
            }
          }
        ]
    

    如果您想明智地过滤用户,您可以添加 { $match : { "userId" : id}} 作为聚合中的第一个管道。

    【讨论】:

      猜你喜欢
      • 2016-10-14
      • 2016-07-11
      • 2018-09-17
      相关资源
      最近更新 更多