[SOLVED] Mongodb – match all items in array of strings field

Issue

This Content is from Stack Overflow. Question asked by Emad Jumaah

I am trying match documents where all items in field colors included in query list provided.

   {id: 1, colors: ["red"] },
   {id: 2, colors: ["blue", "red"] },
   {id: 3, colors: ["red", "blue", "green" ] },
   {id: 4, colors: ["black", "blue", "green" ] },

if the query [red] it will match items 1 if query [red, blue] it should match 1,2 if query [blue, green, red] it should match 3

all items in document should be in the query list

How can I do it in Mongodb



Solution

Query

  • i think you want colors to be subset of the query

Playmongo

aggregate(
[{"$match": {"$expr": {"$setIsSubset": ["$colors", ["red", "blue"]]}}}])


This Question was asked in StackOverflow by Emad Jumaah and Answered by Takis It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?