mongodb - 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
但我找不到一种方法来设置用户好恶的联合,然后是所有产品的区别。
解决方案
db.user.aggregate([{
$lookup: {
from: "product",
pipeline: [{
$match: {
$or: [{
likes: {
$in: [ < ids or whatever > ]
}
}, {
dislikes: {
$in: [ < ids or whatever > ]
}
}]
}
}],
as: "nameofthevariable"
}
}])
基本上编写一个查找作为左外连接从产品集合中获取喜欢或不喜欢的值。$in 允许您在这种情况下根据要求输入多个值。
推荐阅读
- javascript - 为什么我页面中的一个选项卡没有像其他选项卡一样提供反馈?
- python - Python: Reason for the name parameter when defining a type or named tuple
- javascript - Node.js - 将大量 PNG 图像读入数组的最佳选择?
- python - 为什么我在解析数据帧时会收到错误,但当它是单行时却没有?
- android - 如何通过firebase实时数据库在android studio的textview中指定其中一个来从一组数据中检索特定数据?
- react-native - undefined 不是 react native 中的对象(评估'g.ThemeColors.light'),expo.io
- c# - 如何在 xaml 中显示具有特定有效小数的货币?
- python-3.x - Python从文本中解析某些单词
- flutter - 我如何访问我的 API 请求类(无小部件类)中的 bloc
- r - 单击 RUN 和 SOURCE 时 R 中的不同输出(Rstudio 中的 RUN 和 SOURCE 选项卡有什么区别))