0

How can i use merge array to a new array from a detail document there is an example of data

Example of result detail

[{
    country: 'USA',
    val: 500,
    items: [
        {val:50, ...manyFieldsToIgnore},
        {val:30, ...manyFieldsToIgnore},
        {val:110, ...manyFieldsToIgnore},
    ]
}];

Output expected

{ items:[ 
    {
        country: 'USA',
        newNameValue: 500,
    },
    {
        country: 'USA',
        newNameValue: 50,
    },
    {
        country: 'USA',
        newNameValue: 30,
    },
    {
        country: 'USA',
        newNameValue: 110,
    },
};

im try to use $project and $concatArrays but i dont know how to set the new field(country) in details and change their key names

$project: {
    'root.country': '$country',
    items: concatArrays[ '$items'],
},
$project: {
    payments: concatArrays[ '$items', ['$root'] ],
}
0

2 Answers 2

2

The following aggregation returns the desired result. Note the usage of the Aggregation Array Operators - $map and $concatArrays:

db.test.aggregate([
  { 
      $addFields: {
          items: { 
             $map: { 
                 input: "$items", 
                 in: { country: "$country", newNameVal: "$$this.val"  } 
             }
          }
      }
  },
  { 
      $project: { 
          items: { 
              $concatArrays: [ [ { country: "$country", newNameVal: "$val" } ],  "$items" ]
          } 
      }
  }
])
Sign up to request clarification or add additional context in comments.

Comments

1

You can try,

  • $addFields to add country in items array
  • $project to concat 2 arrays one is outer val and country and second is items array using $concatArrays
db.collection.aggregate([
  { $addFields: { "items.country": "$country" } },
  {
    $project: {
      items: {
        $concatArrays: [
          [
            {
              val: "$val",
              country: "$country"
            }
          ],
          "$items"
        ]
      }
    }
  }
])

Playground

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.