【问题标题】:MongoDb Update only one value from arrayMongoDb 仅更新数组中的一个值
【发布时间】:2015-07-18 23:25:44
【问题描述】:

我在 mongodb 中有一个集合,看起来像这样。

"_id" : ObjectId("554c5397ccfff21e103c9869"),
"name" : "test",
"color" : [
    "552ced22ccfff2d8183c986a_Jellow",
    "551fdd24ccfff2362e3c9869_test"
],
"updated_at" : ISODate("2015-05-08T06:11:35.303Z"),
"created_at" : ISODate("2015-05-08T06:11:35.303Z")

我只想更新数组中的一个值 color 但是当我尝试更新数组时,它会从颜色数组中删除所有值并将其替换为新值。 这是代码。 (我正在为 LARAVEL 使用 JESSENGER MONGODB 包)

$query->where($field,'regexp','/^('.$id.')_.*/')->update([$field=>$id.'_'.$name]);

我该怎么做??

【问题讨论】:

    标签: php arrays mongodb laravel jenssegers-mongodb


    【解决方案1】:

    您想要做的是,将您的架构更改为 {key: value} 对,然后按照此tutorial,这将帮助您解决问题。 您可以从颜色数组中获取所有值并替换为新值,然后更新您的文档(我不会这样做,因为这是一种肮脏的方法!)。

    编辑

    嘿,巴德!我在 jenssenger 文档上创建了这个:


    推送

    将项目添加到数组中。

    DB::collection('users')->where('name', 'John')->push('items', 'boots');
    DB::collection('users')->where('name', 'John')->push('messages', array('from' => 'Jane Doe', 'message' => 'Hi John'));
    

    如果不想重复项,将第三个参数设置为true:

    DB::collection('users')->where('name', 'John')->push('items', 'boots', true);
    

    拉动

    从数组中删除一个项目。

    DB::collection('users')->where('name', 'John')->pull('items', 'boots');
    DB::collection('users')->where('name', 'John')->pull('messages', array('from' => 'Jane Doe', 'message' => 'Hi John'));
    

    【讨论】:

      【解决方案2】:

      您需要使用$set 运算符。不确定它在 Jessenger Mongodb 中是如何完成的,但可能类似于:

      $query->where($field,'regexp','/^('.$id.')_.*/')
            ->update(['$set' => [ $field=>$id.'_'.$name]]);
      

      【讨论】:

        【解决方案3】:

        为什么不这样更改您的数据:

        "_id" : ObjectId("554c5397ccfff21e103c9869"),
        "name" : "test",
        "color" : [
            { "id":"552ced22ccfff2d8183c986a", "name":"Jellow"},
            { "id":"551fdd24ccfff2362e3c9869", "name":"test"}
        ],
        "updated_at" : ISODate("2015-05-08T06:11:35.303Z"),
        "created_at" : ISODate("2015-05-08T06:11:35.303Z")
        

        然后你可以通过 id 更新元素。

        【讨论】:

        • 我无法更改架构... :(
        猜你喜欢
        • 1970-01-01
        • 2011-03-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多