How do i change MongoDB JSON data to array

Viewed 45

I need to update the MongoDB field with the array of objects where JSON object to be updated with as an array

if I have something like this in MongoDB

 "designSectionContents" : [
        {
            "_id" : "5bae17ecbd7595540145ec98",
            "type" : "subSection",
            "columns" : [
                {
                    "0" : {
                        "itemId" : "5b7465980783d9a37058f160",
                        "type" : "field"
                    }
                },
                {
                    "0" : {
                        "itemId" : "5b7465630783d9a37058f15c",
                        "type" : "field"
                    }
                },
                {
                    "0" : {
                        "itemId" : "5b7465810783d9a37058f15e",
                        "type" : "field"
                    }
                }
            ],
            "subSectionContentLayout" : {
                "labelPlacement" : "Top",
                "columns" : 3
            }
        }
        ]

I want to change the above snippet to below in MongoDB

"designSectionContents" : [
        {
            "_id" : ObjectId("5bae17ecbd7595540145ec98"),
            "type" : "subSection",          
            "columns" : [
                [
                    {
                        "itemId" : "5b7465980783d9a37058f160",
                        "type" : "field"
                    }
                ],
                [
                    {
                        "itemId" : "5b7465630783d9a37058f15c",
                        "type" : "field"
                    }
                ],
                [
                    {
                        "itemId" : "5b7465810783d9a37058f15e",
                        "type" : "field"
                    }
                ]
            ]
        }
        ]

curly braces opening and closing tag has to be changed to array

1 Answers

This should work:

db.collection.aggregate([
  {
    "$project": {
      "designSectionContents": {
        "$map": {
          "input": "$designSectionContents",
          "as": "designSectionContent",
          "in": {
            "_id": "$$designSectionContent._id",
            "type": "$$designSectionContent.type",
            "columns": {
              "$map": {
                "input": "$$designSectionContent.columns",
                "as": "inp",
                "in": [
                  "$$inp.0"
                ]
              }
            }
          }
        }
      }
    }
  }
]);

Here's the working link.

Related