Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDb array intersection

Tags:

mongodb

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?

like image 952
ldsenow Avatar asked Apr 17 '26 13:04

ldsenow


1 Answers

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.

like image 147
Aaron Dufour Avatar answered Apr 20 '26 05:04

Aaron Dufour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!