0

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

2 Answers 2

2

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');
Sign up to request clarification or add additional context in comments.

Comments

1

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" }

4 Comments

Nice. But how can I pull from an array of a specific document?
well, when using modifier operators you do not need to specify whole document you need to specify only criteria and specify field which you need to modify. In terms of PHP this would look like: $coll->update(array('username' => 'jamesbond', array('$pull' => array('items' => 5678)));
Ok. But what does that look like using Alex Bilbies library? This does not work: $this -> mongo_db -> pull ('items', $pull) -> update ('market.carts', $query);
Sorry I do not know anything about this library :( solutions I posted work in mongo shell and PHP driver.

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.