我正在尝试找到一种方法,让自己获得尽可能干净的代码来使用多个复杂查询。
我在 MongoDB 中有 2 个文档。 第一个是关注者,第二个是事件。
第一个查询:获取特定用户的所有关注者。 第二个查询:获取所有关注者的所有事件并按日期排序。
我不知道如何进行第二个查询。
也许是这样的:
Event.find({ "$or" : [
{
'userId': followers[0].id,
},
{
'userId': followers[1].id,
},
{
'userId': followers[2].id,
},
]});
但是对我来说这并不是一个非常干净的代码。
最佳答案
我认为您需要的是 $in
运算符(operator)。 $in
运算符仅采用一个索引,而 $or
运算符需要更多(每个子句一个)。 documentation还明确指出:
When using $or with that are equality checks for the value of the same field, use the $in operator instead of the $or operator.
您可以按如下方式修改查询:
var userIds = [followers[0].id, followers[1].id, followers[2].id];
Event.find({ 'userId': { $in: userIds } }, function(err, result){ ... });
或者正如 Neil Lunn 所建议的,另一种解决方法是使用 native 映射方法来生成所需用户 ID 的数组:
Event.find({
"userId": {
"$in": followers.map(function (follower){
return follower.id
}))
}
}, function(err, result){ ... });
关于javascript - 使用 $or 在 mongoose 中复杂化多个查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28852745/