1

I have two documents (obtained by other steps in an aggregation pipeline):

{
  '_id': '2021-01-04',
  'value': 1234.55
},
{
  '_id': '2021-01-05',
  'value': 345.67
}

I would now like to convert these two documents into an array that would look like this:

[
  { '2021-01-04': 1234.55 },
  { '2021-01-05': 345.67  }
]

I've tried to first convert the key/value pairs using a $group stage like so:

$group: {
  _id: null,
  data: {
    $push: {
      "k": "$_id",
      "v": "$value"
    }
  }
}

This yields:

[
  {
    "_id": null,
    "data": [
      {
        "k": "2019-01-04",
        "v": 1234.55
      },
      {
        "k": "2019-01-05",
        "v": 345.67
      }
    ]
  }
]

While this would be useful as input for $arrayToObject, I don't want an object (as I need the objects to be ordered), but I cannot see how to get from here to the desired final output.

0

1 Answer 1

1
  • $sort order by _id in ascending order
  • $arrayToObject convert k and v array to object format
  • $group by null and push above converted object in data
db.collection.aggregate([
  { $sort: { _id: 1 } },
  {
    $group: {
      _id: null,
      data: {
        $push: {
          $arrayToObject: [
            [{ k: "$_id", v: "$value" }]
          ]
        }
      }
    }
  }
])

Playground

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

1 Comment

Thank you @turivishal. It seems however, that your first solution returns two documents (I would like one containing an array), and the second one returns an object instead of an array. Maybe I've formulated my problem insufficiently, but I'd like to obtain one document containing an array with two objects.

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.