McSim
McSim

Reputation: 1

Removing an element from an array by index corresponding to the index of an element removed from another array

There is ia part of the document of the collection Collection1 in MongoDb.

"array1": [
  "060030909",
  "200",
  "32004"
],
"array2": [
  "aaa",
  "bbb",
  "xxx"
]

It is necessary to find all documents in collection "Collection1" where the array array1[] contains the element "32004", remove it, and also remove the corresponding element in the array2[] array by the index matching the one of the removed element in array1[].

The result must be:

"array1": [
  "060030909",
  "200"
],
"array2": [
  "aaa",
  "bbb"
]

in all documents of the collection.

How can it be done first of all using MongoTemplate? Thanks

Upvotes: -1

Views: 38

Answers (1)

Wernfried Domscheit
Wernfried Domscheit

Reputation: 59446

Try this one:

db.collection.aggregate([
   {
      $set: {
         array1: { $filter: { input: "$array1", cond: { $ne: ["$$this", "32004"] } } },
         array2: {
            $let: {
               vars: {
                  index: { $indexOfArray: ["$array1", "32004"] }
               },
               in: {
                  $concatArrays: [
                     { $slice: ["$array2", "$$index"] },
                     { $slice: ["$array2", { $add: ["$$index", 1] }, { $size: "$array2" }] }
                  ]
               }
            }
         }
      }
   }
])

array1 is simple, operator $filter removes element "32004"

For array2 it first find the index of element "32004". Then it concatenate two array slices "up-to" and "from plus 1" the found element.

Note, it removes only the first occurrence of "32004". If the array may contain the value multiple times, then you need to do some extra work.

Upvotes: 2

Related Questions