2

I've got a collection like this:

{
  name: "A Name",
  answers: [
    {order: 1},
    {order: 2}, 
    {order: 3}
  ]
}

What I want to do is to add a new filed id to each element of the answers array based on the value of the order property - I want just to clone it, so the output is

{
  name: "A Name",
  answers: [
    {order: 1, id: 1},
    {order: 2, id: 2}, 
    {order: 3, id: 3}
  ]
}

I looked at this post and this one too, but I don't know how to combine them to work properly for subdocuments.

In MongoDB documentation for the aggregate method, I found a simple example of how to update embedded documents here, but I have no idea how to use the order property instead of a fixed term. The following tries seem not to work as I need:

db.collection.aggregate([
  {
    $addFields: {
      "answers.id": "answers.$.order" 
    }
  }
])

db.collection.aggregate([
  {
    $addFields: {
      "answers.id": "$answers.order" 
    }
  }
])

Is it possible to achieve the expected result with the `aggregate method?

Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
Jakub Małecki
  • 483
  • 4
  • 14

1 Answers1

3

Demo - https://mongoplayground.net/p/M79MV6-Zp4C

db.collection.aggregate([
  {
    $set: {
      answers: {
        $map: {
          input: "$answers",
          as: "answer",
          in: {  $mergeObjects: [ "$$answer", { id: "$$answer.order" } ]
          }
        }
      }
    }
  }
])

Updated Demo - https://mongoplayground.net/p/iyqIPGQ5-ld

db.collection.aggregate([
  {  $unwind: "$answers" },
  {
    $group: {
      _id: "$_id",
      answers: { $push: { order: "$answers.order", id: "$answers.order" } },
      name: { $first: "$name" } // preserve properties add them to the group pick 1st value
    }
  }
])

Demo - https://mongoplayground.net/p/Ln5CcmT-Kkm

db.collection.aggregate([
  { $unwind: "$answers" }, // break into individuals documents
  { $addFields: { "answers.id": "$answers.order" } }, // copy order value to id
  { $group: { _id: "$_id", answers: { $push: "$answers" } } } // join and group it back
])

If you want to sort n get id from index

Demo - https://mongoplayground.net/p/6U_sRYWHtDR

db.collection.aggregate([
  { $sort: { "answers.order": 1 } },
  { $unwind: { path: "$answers", includeArrayIndex: "index" } },
  { $group: { _id: "$_id", answers: { "$push": {  order: "$answers.order", id: { $add: [ "$index", 1 ] } } } } }
])
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107