Mongoose find array item in stored array

I have a document that stores an array of ids referencing a different collection:

{
  title: 'Title of the document',
  categories: [
    { _id: 1 },
    { _id: 2 },
    { _id: 3 },
    { _id: 4 },
  ]
}

Now I want to be able to find all the documents that have at least one of the categories that I pass into an array:

categories: [1, 3, 4]

I have searched stackoverflow and the MongoDB documentation, but I didn't find how to implement this.

Upvotes: 0

Views: 72

Answers (1)

Kristian Salo
Kristian Salo

Reputation: 360

I think the $in operator is what you are looking for. It selects documents where the value of a field equals any value in the specified array. Mongo documentation has a helpful page for it with a section for querying values in an array.

You will also need to use dot notation to query for the _id field of the categories array. The docs also have a page for querying an array of embedded documents, which is what you are doing here (you are querying an array of category documents).

For your case, your query object should probably be something like

{ 'categories._id' : { $in: [1, 3, 4] } }

Upvotes: 1

Related Questions