Home > front end >  Transform objects into key/value array mongodb
Transform objects into key/value array mongodb

Time:02-06

I have this data:

[
  {
    "_id": "0001",
    "n1": "0001",
    "n2": 1234
  },
  {
    "_id": "0002",
    "n1": "0002",
    "n2": 9876
  }
]

What's the best way to transform it into this, using aggregation framework?:

[
  {
    "_id": "0001",
    "lookupFields": [
      {
        "n": "n1",
        "v": "0001"
      },
      {
        "n": "n2",
        "v": 1234
      }
    ]
  },
  {
    "_id": "0002",
    "lookupFields": [
      {
        "n": "n1",
        "v": "0002"
      },
      {
        "n": "n2",
        "v": 9876
      }
    ]
  }
]

Thanks for your precious help

CodePudding user response:

db.collection.aggregate([
{
  $project: {
    n: {
      n1: "$n1",
      n2: "$n2"
    }
  }
},
{
  $project: {
    lookupFields: {
      $objectToArray: "$n"
    }
  }
},
{
  $addFields: {
    lookupFields: {
      $map: {
        input: "$lookupFields",
        as: "lf",
        in: {
          n: "$$lf.k",
          v: "$$lf.v"
        }
      }
    }
  }
 }
])

explained:

  1. project the n1&n2 fields inside object n
  2. project the object n as new field lookupFileds as array.
  3. map to rename the array object keys k,v to n,v as requested

playground

  •  Tags:  
  • Related