1

I have an array in a mongodb collection and want to remove one element from it with the index, didnt found how to make it, or an operator for it...

document example:

    {
    "_id": "<someID>",
    "array": [
      {
        "elemt": 1
      },
      {
        "elemt": 2,
      },
      {
        "elemt": 2,
      }]
    }

(duplicates can occur - and dont want to delete these duplicates)

and i want to achive that an element can be removed with the index of it...

Using:

  • NodeJS 8.9
  • Mongodb 3.4
  • (npm) mongodb (native)
  • Visual Studio 17
hasezoey
  • 998
  • 9
  • 24
  • It's not very clear... Do you want to remove duplicate element from your array? Or do you want to remove the element at a specific index of the array ? – felix Jan 15 '18 at 11:50
  • i want to remove an element with the index of it, and not to remove duplicates, with that i meant: duplicates can occur - and dont want to delete these duplicates – hasezoey Jan 15 '18 at 11:58
  • didnt found this before, thanks, but now: how to insert the index? i cant use the templated strings? – hasezoey Jan 15 '18 at 12:07

1 Answers1

5

I have a 2-step solution to achieve what you described.

  1. Set your array's element to null
  2. Find null element and $pull it from your array.

    db.collection.update({}, {$unset : {"array.2" : 1 }});
    db.collection.update({}, {$pull : {"array" : null }});
    

    You can specify the _id in the query. You can't use string templates to specify the index in your query. It will throw out an error "Unexpected template string". You can use computed property:

    var arrIndex = `array.${index}`;
    /* ... */
    db.collection.update({}, {$unset : {[arrIndex] : 1 }});
    

or just wrap your string literal in brackets [], like this: [array.${index}].

Tomasz Bubała
  • 2,093
  • 1
  • 11
  • 18