MongoDB 聚合框架匹配 OR

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16902930/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 13:15:30  来源:igfitidea点击:

MongoDB aggregation framework match OR

mongodbaggregation-framework

提问by Gergely Németh

Is it possible to do an OR in the $match?

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

I mean something like this:

我的意思是这样的:

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

回答by Sammaye

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

Like so, since the $matchoperator just takes what you would normally put into the find()function

像这样,因为$match操作符只需要你通常会放入find()函数中的内容

回答by Amol M Kulkarni

In this particular case, where you are $or-ing the same field, the $inoperator would be a better choice, also because it increases readability:

在这种特殊情况下,你在哪里$or-ing同一领域中,$in运营商将是一个更好的选择,也因为它增加了可读性:

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

According to the MongoDB docs, using $inis recommended in this case:

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

$or versus $in

When using $or with <expressions> that are equality checks for the value of the same field, use the $in operator instead of the $or operator.

$or 与 $in

将 $or 与 <expressions> 一起使用时,要对同一字段的值进行相等检查,请使用 $in 运算符而不是 $or 运算符。

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

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