A
A
Andrey2020-07-22 15:20:55
MongoDB
Andrey, 2020-07-22 15:20:55

How to merge document values ​​into one array in mongodb?

I'm trying to figure out how to interact with data in mongo and transform the response as I see fit.

For example, there is input data. foo - array of numbers, bar - optional number

{ _id : 0, foo: [], bar: 1 },
    { _id : 1, foo: [2, 3], bar: 4 },
    { _id : 3, foo: [5, 6], bar: undefined }


The task is to combine these values ​​and present them in a flat form in one array.
That is, I expect the output . Is there an elegant way to do this? If I understand correctly, there are aggregation mechanisms, but I still don’t understand how to prepare them. I would really appreciate an answer with at least a brief explanation of the action. Thanks
[1, 2, 3, 4, 5, 6]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
hzzzzl, 2020-07-24
@kvaak

without aggregation, nowhere
, collected in mongo compass

db.collection.aggregate([
  {
    '$addFields': {   // новое поле nums
      'nums': {
        '$concatArrays': [  // соберем из foo bar
          '$foo', [ '$bar' ]
        ]
      }
    }
  }, {
    '$project': {  // только оно нам нужно
      'nums': 1
    }
  }, {
    '$unwind': {  // ВСЕ номера
      'path': '$nums'
    }
  }, {
    '$match': {  // уберем пустые строки и null и прочий мусор
      'nums': {
        '$type': 'number'
      }
    }
  }, {
    '$group': {  // addToSet то есть только уникальные
      '_id': null, 
      'nums': {
        '$addToSet': '$nums'
      }
    }
  }, {  // здесь можно остановиться
    '$unwind': {  // дальше только чтобы отсортировать, потому что сет не будет отсортирован
      'path': '$nums'
    }
  }, {
    '$sort': {
      'nums': 1
    }
  }, {
    '$group': {
      '_id': null, 
      'nums': {
        '$push': '$nums'
      }
    }
  }
])

5f1b310a5df58208046016.png

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question