Home > front end >  Mongodb - match all items in array of strings field
Mongodb - match all items in array of strings field

Time:09-18

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 should match items 1 if query [red, blue] it should match 1,2 if query [blue, green, red] it should match 1,2,3

all items in colors field should be in the query list

How can I do it in Mongodb

CodePudding user response:

Query

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

Playmongo

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