Is there a way to project fields base on a regex?

Lets say I have a collection with documents that looks like this
{
_id:
list1:
list2:
other:

}

I can have a bunch of list, in some document I have 2 and in others up to 10. Is there a way I can query with a projection so I only have list1, up to listX but not every other fields? I tried a lot of different aggregate using a regex but so far got no luck.

Thank you!

Hi Robert,

I tried this idea in my testing environment, please check if the below achieves your goal:

// sample documents with different number of field starting with list and also added other fields
db.testregex.find()
[
  {
    _id: ObjectId("6582f2f0978e9e79b39b63a6"),
    list1: 1,
    list2: 2,
    another: 'another text'
  },
  {
    _id: ObjectId("6582f2fa978e9e79b39b63a7"),
    list1: 1,
    list2: 2,
    list3: 3,
    another: 'another text'
  }
]

I executed the below aggregation based on the regex ^list:

db.testregex.aggregate([
...     {
...         $project: {
...             filteredFields: {
...                 $arrayToObject: {
...                     $filter: {
...                         input: { $objectToArray: "$$ROOT" },
...                         as: "field",
...                         cond: { $regexMatch: { input: "$$field.k", regex: '^list' } }
...                     }
...                 }
...             }
...         }
...     }
... ])
[
  {
    _id: ObjectId("6582f2f0978e9e79b39b63a6"),
    filteredFields: { list1: 1, list2: 2 }
  },
  {
    _id: ObjectId("6582f2fa978e9e79b39b63a7"),
    filteredFields: { list1: 1, list2: 2, list3: 3 }
  }
]

Regards,
Mohamed Elshafey

Hi Mohamed!

Thank you for your reply. This works pretty good.

Is there any way to have the output more something like this? Or do I have to use the filteredFields?

{
  _id: ObjectId("6582f2f0978e9e79b39b63a6"),
  list1: 1, 
  list2: 2 
}

Thank you in advance