我的代码:
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);
};
Run Code Online (Sandbox Code Playgroud)
结果汇总为:
[{"$match":{"_id":{"$nin":["5c7bb1d08f999f326151df49","5c7bb1d08f999f326151df49"]},"category":{"$in":["Test"]}}},{"$sample":{"size":1}}]
Run Code Online (Sandbox Code Playgroud)
按类别过滤工作正常。但我的$nin只是忽略了。我必须如何使用$ninwith_id来省略不需要的文件?
_id 在 mongoDb 通常是一个 ObjectId which is a 24 charachter hexadecimal unique key.
您可以将字符串 _id 转换为 ObjectId 然后查询
[{"$match":{"_id":{"$nin":[ObjectId("5c7bb1d08f999f326151df49"),ObjectId("5c7bb1d08f999f326151df49")]},"category":{"$in":["Test"]}}},{"$sample":{"size":1}}]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
923 次 |
| 最近记录: |