gpt4 book ai didi

php - MongoDb 只更新数组中的一个值

转载 作者:可可西里 更新时间:2023-11-01 09:35:58 25 4
gpt4 key购买 nike

我在 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]);

我应该怎么做。??

最佳答案

你想要做的是,将你的架构更改为 {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'));

关于php - MongoDb 只更新数组中的一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30117164/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com