提问者:小点点

猫鼬聚合IFID匹配


我有一个查询,在视频模型中查找,得到了视图,但是我需要那些视图根据userId,像userId=“1xxxxxxxx13”,这可能吗?

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

quer,给我零视图,但有视图,有视图,从这个用户ID的视频,这里是schema

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);

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


共1个答案

匿名用户

看起来您正在计算每个用户的视图。

您可以按照下面的方式进行操作。 按用户id分组并计数视图。 它返回用户视图计数

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

如果要按用户方式筛选,可以添加{$match:{“userid”:id}}作为聚合中的第一个管道。