1

inspired by another question, I looked for a common practice for inserting an item into an array at a specific index inside a pipeline, and could not find one. Assuming my document looks like:

[
  {
    _id: ObjectId("62c2e94e65f32725f8f62b79"),
    updatedAt: ISODate("2022-06-29T13:10:36.659Z"),
    createdAt: ISODate("2022-06-29T08:06:51.264Z"),
    userID: 1,
    myImage: "imageC",
    images: [
      "imageA",
      "imageB",
      "imageD",
      "imageE",
      "imageF"
    ]
  }
]

And I want to insert the value in field myImage to images array, specificaly at index 2, so the expected result is an updated document:

[
  {
    _id: ObjectId("62c2e94e65f32725f8f62b79"),
    updatedAt: ISODate("2022-06-29T13:10:36.659Z"),
    createdAt: ISODate("2022-06-29T08:06:51.264Z"),
    userID: 1,
    myImage: "imageC",
    images: [
      "imageA",
      "imageB",
      "imageC",
      "imageD",
      "imageE",
      "imageF"
    ]
  }
]
nimrod serok
  • 14,151
  • 2
  • 11
  • 33

1 Answers1

1

This can be done using an aggregation pipeline or an update with pipeline. In this case the simple option is an update pipeline.

The idea here is to use the $size of the $$value in the $reduce step to find the right place to insert the item into:

db.collection.update(
{userID: 1},
[
  {$set: {
      images: {
        $reduce: {
          input: "$images",
          initialValue: [],
          in: {$concatArrays: [
              "$$value",
              {$cond: [
                  {$eq: [{$size: "$$value"}, index]},
                  ["$myImage", "$$this"],
                  ["$$this"]
                ]
              }
            ]
          }
        }
      }
    }
  }
])

See how it works on the playground example

nimrod serok
  • 14,151
  • 2
  • 11
  • 33