【问题标题】:Complex multiple queries in mongoose with $or使用 $or 在 mongoose 中进行复杂的多个查询
【发布时间】:2015-05-05 08:10:07
【问题描述】:

我正在尝试找到一种方法,让自己的代码尽可能干净,以使用多个复杂的查询。

我在 MongoDB 中有 2 个文档。 第一个是关注者,第二个是事件。

第一个查询:获取特定用户的所有关注者。 第二个查询:获取所有关注者的所有事件并按日期排序。

我不知道如何进行第二个查询。

可能是这样的:

Event.find({ "$or" : [
                        {
                            'userId': followers[0].id,
                        },
                        {
                            'userId': followers[1].id,
                        },
                        {
                            'userId': followers[2].id,
                        },
                        ]});

但这对我来说并不是一个非常干净的代码。

【问题讨论】:

  • 我认为您需要的是$in 运算符; var userIds = [followers[0].id, followers[1].id, followers[2].id]; Event.find({ 'userId': { $in: userIds } }, function(err, result){ ... });
  • @chridam 对我来说似乎是一个“答案”。特别是如果您能解释$or$in 的关系。我只是想:{ "userId": { "$in": followers.map(function(follower) { return follower.id })) } }
  • @NeilLunn 感谢您的建议,在这种情况下我认为map 函数更可取。

标签: javascript node.js mongodb mongoose mongodb-query


【解决方案1】:

我认为您需要的是 $in 运算符。 $in 运算符只需要一个索引,而$or 运算符需要更多(每个子句一个)。 documentation 还明确指出:

当使用 $or 时,这是对 相同字段的值,使用 $in 运算符而不是 $or 运算符。

您可以按如下方式修改您的查询:

var userIds = [followers[0].id, followers[1].id, followers[2].id]; 
Event.find({ 'userId': { $in: userIds } }, function(err, result){ ... });

或者正如 Neil Lunn 建议的那样,另一种解决方法是使用本机 map 方法来生成所需用户 ID 的数组:

Event.find({
     "userId": {
          "$in": followers.map(function (follower){
               return follower.id
           }))
     }
}, function(err, result){ ... });

【讨论】:

  • 实际上并不是真的“将”使用多个索引,因为优化器会清楚地计算出可以使用单个索引,因为它都是关于同一个字段的。关键是$or$in 在与同一字段上的简单值或正则表达式一起使用时实际上是相同的形式。所以$in$or 就像$all$and
  • @NeilLunn 你说的完全正确,还会指出查询优化器处理$in 的效率更高。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-03
  • 2016-03-04
  • 2017-05-22
  • 2017-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多