【发布时间】:2019-07-24 22:51:50
【问题描述】:
我的代码:
questionSchema.statics.getRandomByUser = function getRandomByUser(user) {
const aggr = [{ $sample: { size: 1 } }];
console.log(`user.answered = ${user.answered}`);
if (user.answered.length || user.categories.length) {
const match = { $match: {} };
if (user.answered.length) match.$match._id = { $nin: user.answered };
if (user.categories.length) match.$match.category = { $in: user.categories };
aggr.unshift(match);
}
console.log(`aggr = ${JSON.stringify(aggr)}`);
return this.model('question').aggregate(aggr);
};
结果聚合为:
[{"$match":{"_id":{"$nin":["5c7bb1d08f999f326151df49","5c7bb1d08f999f326151df49"]},"category":{"$in":["Test"]}}},{"$sample":{"size":1}}]
按类别过滤效果很好。但我的$nin 只是忽略了。我必须如何使用 $nin 和 _id 来忽略不需要的文档?
【问题讨论】:
-
即使这被标记为[重复],我认为这个问题非常有用,因为它处理 $nin。 $nin 的例子并不多。感谢分享