【问题标题】:Mongoose: Aggregate get documents of field of type array and filter those documents based on a specific fieldMongoose:聚合获取数组类型字段的文档并根据特定字段过滤这些文档
【发布时间】:2021-10-08 18:15:18
【问题描述】:

我有这个架构:

const UserSchema = new Schema({
  following: [
    {
      type: Schema.Types.ObjectId,
      ref: "users",
    },
  ],
  video: {
    type: Schema.Types.ObjectId,
    ref: "videos",
  },
});
module.exports = User = mongoose.model("users", UserSchema);

我想得到:User.following WHERE following.video EXISTS

换句话说,我想获取有视频的特定用户所关注的用户列表。

这是我到目前为止所做的:

const user = await User.aggregate([
  { $match: { _id: ObjectId(user_id) } },
  {
    $lookup: {
      from: "users",
      let: { following: "$following" },
      pipeline: [{ $match: { $expr: { $in: ["$_id", "$$following"] } } }],
      as: "following",
    },
  },
]);
const followed_users = user[0].following;

但是,我找不到根据 video 字段过滤关注用户的方法。
知道如何实现这一目标吗?

【问题讨论】:

    标签: mongodb mongoose aggregation-framework mern mongoose-populate


    【解决方案1】:

    其实我只需要这样做:

      {
          $match: {
            video: { $exists: true },
            $expr: { $in: ["$_id", "$$following"] },
          },
        },
    

    【讨论】:

      猜你喜欢
      • 2021-12-08
      • 1970-01-01
      • 2019-08-19
      • 2019-05-28
      • 1970-01-01
      • 1970-01-01
      • 2020-10-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多