【问题标题】:MongoDB remove item from array from a selected documentMongoDB 从选定文档的数组中删除项目
【发布时间】:2011-11-16 13:01:33
【问题描述】:

我正在使用 Codeigniter 和 Alex Bilbies MongoDB 库开发一个 Web 应用程序。 每个用户都有一个文档,其中包含一个名为phones 的项目,其中包含一组电话号码。如何从选定的用户文档中从数组中拉出一个项目?

感谢大家的帮助!

【问题讨论】:

标签: codeigniter mongodb


【解决方案1】:

当我直接尝试使用 Alex Bilbies MongoDB 库从数组中提取值时,我也遇到了问题。 这种方法对我有用,首先取消设置值,然后拉出所有空值。

希望对你有帮助

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

【讨论】:

    【解决方案2】:

    使用 MongoDB $pull 从数组中删除特定数组项:

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

    【讨论】:

    • 不错。但是如何从特定文档的数组中提取?
    • 好吧,当使用修饰符运算符时,您不需要指定整个文档,您只需指定条件并指定需要修改的字段。就 PHP 而言,这看起来像: $coll->update(array('username' => 'jamesbond', array('$pull' => array('items' => 5678)));
    • 好的。但是使用 Alex Bilbies 库看起来像什么?这不起作用: $this -> mongo_db -> pull ('items', $pull) -> update ('market.carts', $query);
    • 对不起,我对这个库一无所知 :( 我在 mongo shell 和 PHP 驱动程序中发布的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-08
    • 1970-01-01
    • 2017-06-17
    • 2013-07-23
    • 2021-11-18
    • 2012-02-21
    相关资源
    最近更新 更多