MongoDB array element from collection
I have a mongodb object as follows:
array ( '_id' => new MongoId("4cc97fb0247ae8747ec5fefb"), 'posts' => array ( 0 => array ( 'comment' => 'Eamorr', 'fromUname' => 'Eamorr', 'time' => 1288273840, 'UTC' => '2010-10-28T14:50:40+01:00', 'ip' => '127.0.0.1', 'id' => '123lasdfiqwoei28asdf', ), 1 => array ( 'comment' => 'Hello', 'fromUname' => 'Eamorr', 'time' => 1288277023, 'UTC' => '2010-10-28T15:43:43+01:00', 'ip' => '127.0.0.1', 'id' => 'qopqwier982389qwfa', ), 2 => array ( 'comment' => 'Hello', 'fromUname' => 'Anonymous', 'time' => 1288283506, 'UTC' => '2010-10-28T17:31:46+01:00', 'ip' => '127.0.0.1', 'id' => 'ioqwoeias892398wrf', ), ///// //Want to remove element 3: ///// 3 => array ( 'comment' => 'asdfasadf', 'fromUname' => 'Anonymous', 'time' => 1288283864, 'UTC' => '2010-10-28T17:37:44+01:00', 'ip' => '127.0.0.1', 'id' => 'wwwwwiasdfn234oiasf', ), 4 => array ( 'comment' => 'asdfasdfasdf', 'fromUname' => 'Anonymous', 'time' => 1288284076, 'UTC' => '2010-10-28T17:41:16+01:00', 'ip' => '127.0.0.1', 'id' => '290qwefoiqweproiqwerpq', ), 5 => array ( 'comment' => 'ASDF', 'fromUname' => 'Eamorr', 'time' => 1288284331, 'UTC' => '2010-10-28T17:45:31+01:00', 'ip' => '127.0.0.1', 'id' => 'eioqw8923892hasdf', ), 6 => array ( 'comment' => 'ASDF2', 'fromUname' => 'Eamorr', 'time' => 1288284370, 'UTC' => '2010-10-28T17:46:10+01:00', 'ip' => '127.0.0.1', 'id' => '23oaiofsaij234', ), ), 'uname' => 'Eamorr', ) Now I am writing PHP code to delete messages [x]. I am trying to use $ pull to remove an array element.
I have an 'id' 'wwwwwiasdfn234oiasf' (array element 3) and I want to delete this entire array, leaving only 6 elements in the 'posts' array.
I tried googling search and looking through documentation to no avail ... I still cannot get mongodb syntax hang.
I do all this in PHP, but any language will do, I should be able to do the translation.
Thank you very much in advance,
Solution (in PHP):
$uname=whatever $id=whatever $mongo=new Mongo(); $walls=$mongo->people->walls; $walls->update(array('uname'=>$uname),array('$pull'=>array('posts'=>array('id'=>$id)))); Here's how to do it using the MongoDB shell. You must port it to PHP.
The pull operation consists of the $pull modifier, the selector and expressions .
{ $pull: { fieldSelector: valueExpression } } In your case, the posts field selector, since the array you want to update. Simple English Expression
where the message
idis "wwwwwiasdfn234oiasf"
This means { id: "wwwwwiasdfn234oiasf" } . If we combine all this, you will get the following $pull statement, which will remove the required element from the array:
{ $pull: { posts: { id: "wwwwwiasdfn234oiasf" } } }