0

I have a document structure like this:

{

    "_id" : "1234",           
    "name" : "foo",  
    "bar" : [  
        {"some0":"value0"},  
        {"some1":"value1"},           
        {"some2":"value2"}
    ]   
}

And i just want to delete Objects in the nested "bar" array by its indices within the array e.g. i have an array of indices like [0,2] which should delete "some0" and "some2" from the array.

I'm aware, that Mongo currently has no way to delete values by its index atomically and usually this is used instead:

db.lists.update({}, {$unset : {"bar.0" : 1 }}) 
db.lists.update({}, {$pull : {"bar" : null}})

Question: Is there a more efficient way to do this if my array of to be deleted indices gets quite large (>100) than looping over them manually and do the 2 modifications for each of them.

Community
  • 1
  • 1
Maximilian Körner
  • 846
  • 11
  • 31

2 Answers2

0

There is no straight way of pulling/removing by array index. In fact, this is an open issue http://jira.mongodb.org/browse/SERVER-1014 , you may vote for it.

Only way is what you have written is correct db.lists.update({}, {$unset : {"bar.0" : 1 }}) db.lists.update({}, {$pull : {"bar" : null}})

Piyush.kapoor
  • 6,715
  • 1
  • 21
  • 21
  • My question was, if there is a more efficient way to do this for a large amount of indices than looping over them and do the 2 modifications for each of them. I should make this more clear in the question – Maximilian Körner Jun 24 '16 at 08:57
0

You can use positional $ operator identifies an element in an array to update without explicitly specifying the position of the element in the array

db.lists.update({'bar.some0':'value0'}, {$unset : {"bar.$" : 1 }}) 

some0, some1 you can pass it as dynamic variable

Şivā SankĂr
  • 1,966
  • 1
  • 18
  • 34