How I get documents with dynamic property

Hello! I need Help with some retrieve data

I have a collection like this:

{
    _id: ObjectId("12321323"),
   name: "ageRank",
   filters: ["<25", "25-29"]
},
{
    _id: ObjectId("12321323"),
   name: "age",
   filters: [15, 18, 25]
},

And I want you to give them to me like this:

{
    ageRank: [{filter: "<25"}, {filter: "25-29"} ],
   age:[{filter:"15"}, {filter: "18"},{filter: "25"} ]
}

If anyone can help me I would really appreciate it, thank you very much! :slight_smile:

Hi @Sergi_Ramos_Aguilo and welcome back! :+1:

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.

4 Likes

Works!
Thank you very much! I love this community
:slight_smile:

Cheers

3 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.