首页 > 解决方案 > MongoDB - 查找两个集合之间的差异

问题描述

我有两个收藏:

用户

var UserSchema = new mongoose.Schema({
    likes: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Products' }],
    dislikes: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Products' }],
})

产品

var ProductSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true,
  },
})

我想退回所有不在 User.likes 或 User.dislikes 中的产品。这是我目前的做法:

const user = await User.findById(req.user.id, 'likes dislikes');
let seenProducts = [];

user.likes.forEach(p => {
    seenProducts.push(new mongoose.Types.ObjectId(p));
})

user.dislikes.forEach(p=> {
    seenProducts.push(new mongoose.Types.ObjectId(p));
})

Product.aggregate([
    {
        $match: { _id: { $nin: seenProducts } },
    }
])

它有效,但如果可能,我想切换到使用聚合管道框架来执行此操作。比较两个系列似乎并不容易......我已经尝试了一段时间但没有运气。$setUnion看起来很有希望,$setDifference但我找不到一种方法来设置用户好恶的联合,然后是所有产品的区别。

标签: mongodbmongoosenosqlaggregation-frameworknosql-aggregation

解决方案


db.user.aggregate([{
  $lookup: {
    from: "product",
    pipeline: [{
      $match: {
        $or: [{
          likes: {
            $in: [ < ids or whatever > ]
          }
        }, {
          dislikes: {
            $in: [ < ids or whatever > ]
          }
        }]
      }
    }],
    as: "nameofthevariable"
  }
}])

基本上编写一个查找作为左外连接从产品集合中获取喜欢或不喜欢的值。$in 允许您在这种情况下根据要求输入多个值。


推荐阅读