首页 文章

MongoDB聚合框架匹配OR

提问于
浏览
83

是否可以在$ match中进行OR?

我的意思是这样的:

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

2 回答

  • 136
    $match: { $or: [{ author: 'dave' }, { author: 'john' }] }
    

    像这样,因为 $match 运算符只是采用你通常会放入 find() 函数的内容

  • 65

    在这种特殊情况下,你在 $or -ing相同的字段, $in 运算符将是更好的选择,也因为它增加了可读性:

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

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

    $或vs $ in当使用$或与<expressions>相同的字段值进行相等性检查时,请使用$ in运算符而不是$或运算符 .

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

相关问题