1

I'm trying to use aggregate framework of MongoDB(3.6) to flatten the following data:

array = [
  [1899.99, 241.92, 869.99, 696],
  [2301.45, 100],
  [1468.12, 85.9],
  [14.1],
  [268.59, 27.6, 428.51, 173.85],
  [627.29, 241.92, 413.47, 229.74],
  [1687.58, 100],
  [241.11]
]

And what I need is:

result = [1899.99, 241.92, 869.99, 696, 2301.45, 100, 1468.12, 85.9, 14.1, 268.59, 27.6, 428.51, 173.85, 627.29, 241.92, 413.47, 229.74, 1687.58, 100, 241.11]

I'm using this query:

db.collection.aggregate([
  {
    $match: { code: '11122233344' }
  },
  {
    $project: {
      vencimentos: '$response.operations.expirations.value'
    }
  },
  {
    $unwind: '$vencimentos'
  },
  {
    $group: {
      _id: 'vencimentos',
      vencimentos: { $addToSet: '$vencimentos' }
    }
  },
])

And this is the result of query:

{
  "_id" : "vencimentos",
  "vencimentos" : [
    [1899.99, 241.92, 869.99, 696.11],
    [2301.45, 100],
    [1468.12, 85.9],
    [14.1],
    [268.59, 27.6, 428.51, 173.85],
    [627.29, 241.92, 413.47, 229.74],
    [1687.58, 100],
    [241.11]
  ]
}

Anyone can help me? Thanks.

1 Answer 1

2

Considering the result of your current aggregation, you have to add the following step to get what you need :

{
    $addFields: {
      vencimentos: {
        "$reduce": {
          "input": "$vencimentos",
          "initialValue": [],
          "in": {
            "$concatArrays": [
              "$$this",
              "$$value"
            ]
          }
        }
      }
    }
  }

You can test the result here

Sign up to request clarification or add additional context in comments.

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.