yychzjl
yychzjl

Reputation: 49

restruct document in MongoDB

I have documents structure in mongoDB like this.

{
'identifier': 'testanalysis',
'uuid': 'abc',
'days': [{'day': 20190122, 'value': 1}, {'day': 20190123, 'value': 2}, ]
},
{
'identifier': 'testanalysis',
'uuid': 'xyz',
'days': [{'day': 20190122, 'value': 5}, {'day': 20190123, 'value': 10}, ]
}

I hope to get a result as follows.It seems like group by day and combine uuid and value as an object.

{
    'day': 20190122,
    'result': [
        {'uuid': 'abc', 'value': 1},
        {'uuid': 'xyz', 'value': 5},
    ]
},
{
    'day': 20190123,
    'result': [
        {'uuid': 'abc', 'value': 2},
        {'uuid': 'xyz', 'value': 10},
    ]
}

Upvotes: 0

Views: 32

Answers (1)

Ashok
Ashok

Reputation: 2932

just little bit Aggregation

db.collection.aggregate([
  { $unwind: '$days' },
  { $group: {
      _id: "$days.day",
      day: { $first: "$days.day" },
      result: {
        $push: { 'uuid': '$uuid', 'value': '$days.value' }
      }
    }
  }
])

Upvotes: 1

Related Questions