MongoDB 聚合 - 如何检查文档数组中是否存在特定字段值

标签 mongodb aggregation

我有这个用于 PostsLikeSchema ,我想要实现的是检查用户 id 是否存在于这些 Likes Document 数组中 _user_id

假设我有这个Likes文档数组

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

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

我有这个喜欢架构

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 表达式匹配?或者也许有更好的方法来检查对象数组中存在的值?

最佳答案

终于找到答案了。 事实证明,聚合中存在一个 $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
        }
     }  
   }
])

关于MongoDB 聚合 - 如何检查文档数组中是否存在特定字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66705264/

相关文章:

sorting - ElasticSearch 多级父子聚合

mongodb - Mongodb聚合中基于其他字段值的多个条件的动态新字段值

mongodb - Mongo 查询嵌入式文档中的动态字段

python - 如何在 MongoDb 中创建人类可读的 ID

javascript - 将 "programmatic"数组推送到对象的数组属性

r - 基于逗号聚合列

elasticsearch - 使用大量存储桶在 Elastic 中导航术语聚合

mongodb sort with skip and limit 不根据索引对记录进行排序

node.js - 使用 mongodb-native 删除所有文档

mongodb - 具有多个字段的 Spring Data MongoDB 推送操作不起作用