141

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

3 Answers 3

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

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

Sign up to request clarification or add additional context in comments.

Comments

110

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

7 Comments

According to Mongo docs, this "most effective" way of doing it for equality comparisons such as your example. See docs.mongodb.org/manual/reference/operator/query/or/#_S_or%22
The $in is the way to go
I believe $or is not an aggregation operator.
@PaulShapiro: I hope you did not down voted because of this. For all please consider commenting the reason before down-voting it helps everyone. Here is the reference Boolean Aggregation Operators -> $or
Your answer is not correct, and as you can see, I already commented explaining where and how the answer is incorrect.
|
0
$match : {
$or: [
                {
                    $expr: {
                        $ne: ["$community", ObjectId(id)]
                    }
                },
                {
                    community: {
                        $exists: false
                    }
                }
            ]

}

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.