Search code examples
arraysmongodb

How to extract matching strings from array and create new array


I need to extract strings that contain the word 'DREAMS' from 'STYLE.' and create a new array with it.

MongoDB Documents:

[
  {
    name: "STYLE",
    params: ['DREAMS-FEEDING', 'DREAMS-PARI', 'SOFT']
  }, 
  {
    name: "BRAND",
    params: ['DREAMS', 'FEATHERLINE']
  }
]

The result should be:

['DREAMS-FEEDING', 'DREAMS-PARI']

Solution

  • You can apply the $regex operator to the params array. In the projection, with $filter and $regexMatch operators to filter the element(s) in the array.

    db.collection.find({
      name: "STYLE",
      params: {
        $regex: "DREAMS"
      }
    },
    {
      name: 1,
      params: {
        $filter: {
          input: "$params",
          cond: {
            $regexMatch: {
              input: "$$this",
              regex: "DREAMS"
            }
          }
        }
      }
    })
    

    Demo @ Mongo Playground