【问题标题】:MongoDB - Find Difference Between Two CollectionsMongoDB - 查找两个集合之间的差异
【发布时间】:2021-07-25 12:27:40
【问题描述】:

我有两个收藏:

用户

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 看起来很有希望,但我找不到一种方法来设置用户好恶的联合,然后是所有产品的差异。

【问题讨论】:

    标签: mongodb mongoose nosql aggregation-framework nosql-aggregation


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

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

    【讨论】:

      猜你喜欢
      • 2010-11-24
      • 2019-01-20
      • 1970-01-01
      • 1970-01-01
      • 2015-03-19
      • 1970-01-01
      • 1970-01-01
      • 2014-02-02
      • 2012-02-09
      相关资源
      最近更新 更多