Hi @Sergi_Ramos_Aguilo and welcome back!
I think I got it. At least this is one way to do it.
Maybe not the best but it works I guess.
test [direct: primary] test> db.coll.insertMany([{name: "ageRank", filters: ["<25", "25-29"] }, {name: "age", filters: [15, 18, 25] }])
{
acknowledged: true,
insertedIds: {
'0': ObjectId("63863a1a0721bcd1c687cd29"),
'1': ObjectId("63863a1a0721bcd1c687cd2a")
}
}
test [direct: primary] test> db.coll.find()
[
{
_id: ObjectId("63863a1a0721bcd1c687cd29"),
name: 'ageRank',
filters: [ '<25', '25-29' ]
},
{
_id: ObjectId("63863a1a0721bcd1c687cd2a"),
name: 'age',
filters: [ 15, 18, 25 ]
}
]
test [direct: primary] test> db.coll.aggregate([
... {
... '$project': {
... '_id': 0,
... 'k': '$name',
... 'v': {
... '$map': {
... 'input': '$filters',
... 'as': 'i',
... 'in': {
... 'filter': '$$i'
... }
... }
... }
... }
... }, {
... '$group': {
... '_id': null,
... 'x': {
... '$push': '$$ROOT'
... }
... }
... }, {
... '$project': {
... 'result': {
... '$arrayToObject': '$x'
... }
... }
... }, {
... '$replaceRoot': {
... 'newRoot': '$result'
... }
... }
... ])
[
{
ageRank: [ { filter: '<25' }, { filter: '25-29' } ],
age: [ { filter: 15 }, { filter: 18 }, { filter: 25 } ]
}
]
Here is my pipeline for an easy copy & paste:
[
{
'$project': {
'_id': 0,
'k': '$name',
'v': {
'$map': {
'input': '$filters',
'as': 'i',
'in': {
'filter': '$$i'
}
}
}
}
}, {
'$group': {
'_id': null,
'x': {
'$push': '$$ROOT'
}
}
}, {
'$project': {
'result': {
'$arrayToObject': '$x'
}
}
}, {
'$replaceRoot': {
'newRoot': '$result'
}
}
]
Cheers,
Maxime.