0
votes

I am developing a web app using Codeigniter and Alex Bilbies MongoDB library. Each user got a document that contains an item called phones which contains an array of phone numbers. How can I pull an item out of the array from the selected users document?

Thankful for all help!

2
Mongo has support of $pull out of the box: mongodb.org/display/DOCS/Updating#Updating-%24pullioseb
Yeah, but can I make a pull on a specific array item?Jonathan Clark

2 Answers

2
votes

Even I ran into an issue when directly trying to pull a value from an array using Alex Bilbies MongoDB library. This approach works for me, first unsetting the value, and then pulling all nulls.

Hope this helps

$this->mongo_db->where('items', "5678")->unset_field('items.$')->update('mycollection');
$this->mongo_db->pull('items', NULL)->update('mycollection');
1
votes

Using MongoDB $pull for removing specific array item from array:

> db.mycollection.insert({user: "test", items: [1234, 5678, 91011]});
> db.mycollection.find()
{ "_id" : ObjectId("4ec3b9af8d1ae67f1fb2b30a"), "user" : "test", "items" : [ 1234, 5678, 91011 ] }
> db.mycollection.update({user: "test"}, {$pull: {items: 5678}});
> db.mycollection.find()
{ "_id" : ObjectId("4ec3b9af8d1ae67f1fb2b30a"), "items" : [ 1234, 91011 ], "user" : "test" }