【问题标题】:MongoDB Aggregate - How to check if a specific field value exists in array of documentsMongoDB Aggregate - 如何检查文档数组中是否存在特定字段值
【发布时间】:2021-03-19 21:10:13
【问题描述】:

我有这个LikeSchema 用于Posts,我想要实现的是检查用户id 是否存在于这些喜欢文档的_user_id 数组中

假设我有这个Likes 文档数组

[
  {
    id: 'a',
    _user_id: 'u1',
    _post_id: 'p1'
  },
  {
    id: 'b',
    _user_id: 'u2',
    _post_id: 'p1'
  }
]

如何使用聚合检查用户 ID u1 是否存在于 likes 数组文档中?

我有这个 Like Schema

const LikeSchema = new Schema({
    _post_id: {
        type: Schema.Types.ObjectId,
        ref: 'Post',
        required: true
    },
    _user_id: {
        type: Schema.Types.ObjectId,
        ref: 'User',
        required: true
    },
})

还有我的聚合

const result = await Post.aggregate([
  {
    $match: { privacy: 'public' }
  }, 
  {
    $lookup: {
      from: 'likes',
      localField: '_id',
      foreignField: '_post_id',
      as: 'likes'
    }
  },
  {
     $addFields: {
        isLiked: {
          $in: [req.user._id, '$likes'] // WONT WORK SINCE I STILL HAVE TO MAP AS ARRAY OF _user_id
        }
     }  
   }
])

我想到的解决方案是首先将数组映射为只有用户 ID 值,然后执行 $in 表达式。 如何在聚合阶段从lookup 映射likes 数组,以便它只包含用户ID 值的数组以使$in 表达式匹配?或者也许有更好的方法来检查对象数组中存在的值?

【问题讨论】:

    标签: mongodb aggregation


    【解决方案1】:

    终于找到答案了。 事实证明,聚合中存在 $map 运算符。我就是这样用的

    const result = await Post.aggregate([
      {
        $match: { privacy: 'public' }
      }, 
      {
        $lookup: {
          from: 'likes',
          localField: '_id',
          foreignField: '_post_id',
          as: 'likes'
        }
      }, 
      {
        $addFields: {
           likeIDs: { // map out array of like id's
             $map: {
               input: "$likes",
               as: "postLike",
               in: '$$postLike._id'
             }
           }
        }
      },
      {
         $addFields: {
            isLiked: {
              $in: [req.user._id, '$likeIDs'] // it works now
            }
         }  
       }
    ])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-02
      • 1970-01-01
      • 2020-06-08
      • 2023-01-03
      • 2016-09-09
      • 2018-08-16
      相关资源
      最近更新 更多