MongoDb 只更新数组中的一个值

MongoDb Update only one value from array

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

"_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,这将帮助您解决问题。 OR 你可以从颜色数组中获取所有值并替换为新值,然后更新你的文档(我不会这样做,因为这是一种肮脏的方法!)。

编辑

嘿伙计!我在 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'));

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

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

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

"_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更新元素。