MongoDB聚合框架匹配OR

Ger*_*eth 89 mongodb aggregation-framework

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

我的意思是这样的:

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

Sam*_*aye 155

$match: { $or: [{ author: 'dave' }, { author: 'john' }] }
Run Code Online (Sandbox Code Playgroud)

就像这样,因为$match操作员只需要将您通常放入find()函数中的内容


Amo*_*rni 77

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

$match: { 
  'author': { 
    $in: ['dave','john'] 
  } 
}
Run Code Online (Sandbox Code Playgroud)

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

$或与$ in

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

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

  • $ in是要走的路 (3认同)