给定两个集合,例如:
users:
name
posts:
title
user_id
如何高效查询拥有超过 5 个帖子的用户?
我可以使用 $lookup
进行聚合,但这对于大型数据集来说需要很长时间。
另一个选择是在用户
上维护“postCount”,但我希望避免维护它。
我在 Node 上使用 Mongoose。
最佳答案
使用 $lookup
的高效聚合查询和一个$redact
过滤管道如下:
User.aggregate([
{
"$lookup": {
"from": "posts",
"localField": "_id",
"foreignField": "user_id",
"as": "posts"
}
},
{
"$redact": {
"$cond": [
{ "$gt": [ { "$size": "$posts" }, 5 ] },
"$$KEEP",
"$$PRUNE"
]
}
}
]).exec(function(err, results){
if (err) throw err;
console.log(results);
})
关于node.js - 统计 Mongo 中引用对象的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41825338/