Let's assume we have
post1.tags = [ '1', '2', '3' ];
post2.tags = [ '2', '4', '5' ];
post3.tags = [ '1', '3', '4' ];
post4.tags = [ '1', '3', '4', '5', '6' ];
I'm trying to find posts which are containing 2 or more of the given tags [ '1', '3', '5' ]. The result should be post1, post3 and post4. How can write a mongodb query to achieve this?
It sounds like there might be a better way to implement what you're trying to do, but without more information it's difficult to make high-level suggestions.
Here is a query that will get what you're looking for:
{
$or:
[
{
tags:
{
$all: ['1', '3']
}
},
{
tags:
{
$all: ['3', '5']
}
},
{
tags:
{
$all: ['1', '5']
}
}
]
}
You'll notice that it involves listing every combination of pairs of tags that you're searching for, so it won't scale well to larger queries.
Edit: Simplified the query by using $all instead of $and.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With