My code:
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);
};
In result aggregate is:
[{"$match":{"_id":{"$nin":["5c7bb1d08f999f326151df49","5c7bb1d08f999f326151df49"]},"category":{"$in":["Test"]}}},{"$sample":{"size":1}}]
Filter by category works fine. But my $nin
just ignored. How I must use $nin
with _id
to omit unwanted documents?