-1

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

2
  • 1
    What did you try? Commented Jan 15 at 13:11
  • It is suggested that you refactor your schema to zip the array entries together like this. A simple migration may look like this Commented Jan 15 at 14:41

1 Answer 1

2

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.

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

Comments

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.