3

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.

4
  • You need an index on the tags field. docs.mongodb.com/manual/core/index-multikey Commented Dec 12, 2020 at 10:48
  • I did, but still not work Commented Dec 12, 2020 at 11:40
  • You should probably add the index definition and the query you used to your question. "did not work" is not enough information for anyone to figure out what's going on. Commented Dec 12, 2020 at 11:42
  • Yes, you are right. I added some more details Commented Dec 12, 2020 at 11:58

1 Answer 1

5

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

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

2 Comments

Awesome. It works. Is there any option to that with aggregation too? Or is it recommended to use find?
If your intent is to only find documents, you should favor .find(). If you actually need to do operations like grouping, then you need to use .aggregate(). You can use $in the same way I did inside your $match-clause.

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.