mongoose replace values before index

Viewed 40

I have a collection with an array like this inside of if (array lengths vary)

 "arrayName": [
    {"name": "D", "_id": ObjectId(IDOFD)},
    {"name": "C", "_id": ObjectId(IDOFC)},
    {"name": "B", "_id": ObjectId(IDOFB)},
    {"name": "A", "_id": ObjectId(IDOFA)}
 ]

im trying to replace all the values before a certain element in that array - say I want to replace every element before the element with "_id": ObjectId(IDOFB) (if the element with this id is the last element of the array just push the "replacementValues" array after the specified element) with:

"replacementValues": [
    {"name": "REPLACE 1", "_id": ObjectId(IDOFREPLACE 1)},
    {"name": "REPLACE 2", "_id": ObjectId(IDOFREPLACE 2)}
 ]

this will result in:

"arrayName": [
    {"name": "D", "_id": ObjectId(IDOFD)},
    {"name": "C", "_id": ObjectId(IDOFC)},
    {"name": "B", "_id": ObjectId(IDOFB)},
    {"name": "REPLACE 1", "_id": ObjectId(IDOFREPLACE 1)},
    {"name": "REPLACE 2", "_id": ObjectId(IDOFREPLACE 2)}
 ]

how can I achieve this? Any help would be greatly appreciated!

1 Answers

You can use update with aggregation pipeline starting from MongoDB 4.2,

  • $indexOfArray to get index of input _id in arrayName
  • $add add one in above return index because index start from zero
  • $slice to get all elements that are above return index
  • $concatArrays to concat above return elements and then input replacement array
let replacementValues = [
  { "name": "REPLACE 1", "_id": ObjectId(IDOFREPLACE 1) },
  { "name": "REPLACE 2", "_id": ObjectId(IDOFREPLACE 2) }
];
let _id = ObjectId(IDOFB);

YourSchemaModel.updateOne(
  {}, // put your query
  [{
    $set: {
      arrayName: {
        $concatArrays: [
          {
            $slice: [
              "$arrayName",
              0,
              {
                $add: [
                  { $indexOfArray: ["$arrayName._id", _id] },
                  1
                ]
              }
            ]
          },
          replacementValues
        ]
      }
    }
  }]
)

Playground

Related