Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In mongoDb, how do you remove an array element by its index?

Tags:

mongodb

In the following example, assume the document is in the db.people collection.

How to remove the 3rd element of the interests array by it's index?

{   "_id" : ObjectId("4d1cb5de451600000000497a"),              "name" : "dannie",     "interests" : [       "guitar",       "programming",                "gadgets",       "reading"     ]    } 

This is my current solution:

var interests = db.people.findOne({"name":"dannie"}).interests;   interests.splice(2,1)   db.people.update({"name":"dannie"}, {"$set" : {"interests" : interests}}); 

Is there a more direct way?

like image 963
dannie.f Avatar asked Jan 03 '11 20:01

dannie.f


People also ask

How do I remove an element from an array in MongoDB?

To remove an element, update, and use $pull in MongoDB. The $pull operator removes from an existing array all instances of a value or values that match a specified condition.

Is it possible to remove an index from an array?

Find the index of the array element you want to remove using indexOf , and then remove that index with splice . The splice() method changes the contents of an array by removing existing elements and/or adding new elements. The second parameter of splice is the number of elements to remove.

How do you remove an element from an array and a shift index?

To remove an array element at index i, you shift elements with index greater than i left (or down) by one element. For example, if you want to remove element 3, you copy element 4 to element 3, element 5 to element 4, element 6 to element 5.


1 Answers

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.

The workaround is using $unset and then $pull:

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

Update: as mentioned in some of the comments this approach is not atomic and can cause some race conditions if other clients read and/or write between the two operations. If we need the operation to be atomic, we could:

  • Read the document from the database
  • Update the document and remove the item in the array
  • Replace the document in the database. To ensure the document has not changed since we read it, we can use the update if current pattern described in the mongo docs
like image 147
Javier Ferrero Avatar answered Oct 03 '22 13:10

Javier Ferrero