Hi @Thyme1 - Welcome to the community.
I had a similar approach with the following pipeline using $filter
and $regexMatch
:
{
'$addFields': {
filteredArray: {
'$filter': {
input: '$taste',
cond: {
'$regexMatch': { input: '$$taste', regex: /pep/, options: 'i' }
},
as: 'taste'
}
}
}
}
In my test environment, I had the following documents:
DB>db.coll.find()
[
{
_id: ObjectId("6383fb1931f9fbfd0869f470"),
taste: [ 'pear', 'pepper', 'toffi' ]
},
{
_id: ObjectId("6383fd8f31f9fbfd0869f471"),
taste: [ 'test', 'per', 'toffi' ]
},
{
_id: ObjectId("6383fd9f31f9fbfd0869f472"),
taste: [ 'testpepper', 'toffi' ]
},
{
_id: ObjectId("6383fda631f9fbfd0869f473"),
taste: [ 'testpepper', 'toffi', 'pepper' ]
}
]
The output using the pipeline above:
[
{
_id: ObjectId("6383fb1931f9fbfd0869f470"),
taste: [ 'pear', 'pepper', 'toffi' ],
filteredArray: [ 'pepper' ]
},
{
_id: ObjectId("6383fd8f31f9fbfd0869f471"),
taste: [ 'test', 'per', 'toffi' ],
filteredArray: []
},
{
_id: ObjectId("6383fd9f31f9fbfd0869f472"),
taste: [ 'testpepper', 'toffi' ],
filteredArray: [ 'testpepper' ]
},
{
_id: ObjectId("6383fda631f9fbfd0869f473"),
taste: [ 'testpepper', 'toffi', 'pepper' ],
filteredArray: [ 'testpepper', 'pepper' ]
}
]
result is [{‘taste’:[‘pepper’]},{‘taste’:[‘pepperoni’, ‘pepper’]}]
How to make it a list of distinct values?
Based off the above 4 output documents, could you describe your desired output in regards distinct values?
Regards,
Jason