我有一个mongodb对象如下:
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',
)
现在,我正在编写一些PHP代码来删除帖子[x]。我正在尝试使用$ pull来删除数组元素。
我有'id''wwwwwiasdfn234oiasf'(数组元素3),我想删除这个整个数组元素,只留下'posts'数组中的6个元素。
我尝试使用谷歌搜索并查找文档无济于事...我仍然无法掌握mongodb语法。
我正在用PHP完成所有这些工作,但任何语言都可以,我应该可以进行翻译。
非常感谢,
解决方案(在PHP中):
$uname=whatever
$id=whatever
$mongo=new Mongo();
$walls=$mongo->people->walls;
$walls->update(array('uname'=>$uname),array('$pull'=>array('posts'=>array('id'=>$id))));
答案 0 :(得分:15)
以下是使用MongoDB shell的方法。您应该能够将其翻译成PHP。
拉动操作包括$pull
修饰符,字段选择器和值表达式。
{ $pull: { fieldSelector: valueExpression } }
在您的情况下,字段选择器为posts
,因为那是您要更新的数组。值表达式,用简单的英语,是
帖子的
id
等于“wwwwwiasdfn234oiasf”
这转换为{ id: "wwwwwiasdfn234oiasf" }
。如果我们将所有这些结合起来,您将获得以下$pull
语句,该语句将从数组中删除所需的项目:
{ $pull: { posts: { id: "wwwwwiasdfn234oiasf" } } }