【问题标题】:MongoDB aggregation framework match ORMongoDB 聚合框架匹配或
【发布时间】:2013-05-29 23:15:51
【问题描述】:

可以在 $match 中做 OR 吗?

我的意思是这样的:

db.articles.aggregate(
    { $or: [ $match : { author : "dave" }, $match : { author : "john" }] }
);

【问题讨论】:

    标签: mongodb aggregation-framework


    【解决方案1】:
    $match: { $or: [{ author: 'dave' }, { author: 'john' }] }
    

    就像这样,因为 $match 运算符只接受您通常放入 find() 函数的内容

    【讨论】:

      【解决方案2】:

      在这种特殊情况下,如果您是$or-ing 相同的字段$in 运算符将是更好的选择,还因为它提高了可读性:

      $match: { 
        'author': { 
          $in: ['dave','john'] 
        } 
      }
      

      根据 MongoDB 文档,在这种情况下建议使用 $in

      $or 与 $in

      当使用 $or 和 是相等的 检查同一字段的值,请改用 $in 运算符 $or 运算符。

      https://docs.mongodb.com/manual/reference/operator/query/or/#or-versus-in

      【讨论】:

      • 根据 Mongo 文档,这种“最有效”的方法可以进行相等比较,例如您的示例。见docs.mongodb.org/manual/reference/operator/query/or/#_S_or%22
      • $in 是要走的路
      • 我相信 $or 不是聚合运算符。
      • @PaulShapiro:我希望你没有因此而投反对票。对于所有人,请考虑在否决投票之前评论原因,这对每个人都有帮助。这是参考Boolean Aggregation Operators -> $or
      • 你的答案不正确,正如你所看到的,我已经评论解释了答案在哪里以及如何不正确。
      猜你喜欢
      • 2014-03-04
      • 1970-01-01
      • 1970-01-01
      • 2013-04-25
      • 2013-07-20
      • 2012-09-24
      • 1970-01-01
      • 2020-06-29
      • 2019-01-24
      相关资源
      最近更新 更多