Gergely Németh
Gergely Németh

Reputation: 1435

MongoDB aggregation framework match OR

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" }] }
);

Upvotes: 140

Views: 109922

Answers (3)

md Vasim
md Vasim

Reputation: 1

$match : {
$or: [
                {
                    $expr: {
                        $ne: ["$community", ObjectId(id)]
                    }
                },
                {
                    community: {
                        $exists: false
                    }
                }
            ]

}

Upvotes: 0

Amol M Kulkarni
Amol M Kulkarni

Reputation: 21629

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

Upvotes: 110

Sammaye
Sammaye

Reputation: 43884

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

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

Upvotes: 243

Related Questions