Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS MongoDB Where Array contains any element of Array

I have a collection of content objects. Each document of this collection contains an array with tags:

{
  _id: ....,
  title: 'Title 1',
  details: { ..., tags: ['politic', 'usa'] }
},
{
  _id: ....,
  title: 'Title 2',
  details: { ..., tags: ['art', 'modern'] }
}

The user should be able to filter for tags. For individuals and several. Is there any way to query for that?

Example:

User search for content with one of the following tags:

['politic', 'french']  =>  Title1
['music', 'autumn']    =>  no result
['usa', 'art']         =>  Title1 & Title2
['modern']             =>  Title2

What I tried:

const aggregate = [{ $match: { "details.tags": 'music' } }];
mongodb.collection("content").aggregate(aggregate).toArray();

This works fine for searching by one tag. If I change 'music' to an array like ['music', 'usa'] I don't get any result.

#EDIT1

I added an Index to the collection:

db.content.createIndex( { "details.tags": 1 });

Unfortunately, the aggregation query still returns an empty result. That's why I tried also a find:

db.content.find({"details.tags": ['music', 'usa']})

But also without success.

like image 480
Nico Schuck Avatar asked Feb 24 '26 12:02

Nico Schuck


1 Answers

In order to find multiple values in an array, you should use the $in-operator:

db.collection.find({
  "details.tags": {
    $in: [
      "usa",
      "art"
    ]
  }
})

See this example on mongoplayground: https://mongoplayground.net/p/vzeHNdLhq0j

like image 112
eol Avatar answered Feb 27 '26 02:02

eol



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!