MongoDB aggregation framework match OR

MongodbAggregation Framework

Mongodb Problem Overview


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

I mean something like this:

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

Mongodb Solutions


Solution 1 - Mongodb

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

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

Solution 2 - Mongodb

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

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

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

> $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.

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGergely N&#233;methView Question on Stackoverflow
Solution 1 - MongodbSammayeView Answer on Stackoverflow
Solution 2 - MongodbAmol M KulkarniView Answer on Stackoverflow