MongoDb只更新数组

时间:2015-05-08 06:29:37

标签: php arrays mongodb laravel jenssegers-mongodb

我在 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")

我想只更新数组中的一个值颜色但是当我尝试更新数组时,它会删除颜色数组中的所有值并用新值替换它。 这是代码。 (我正在使用JARENGER MONGODB PACKAGE for LARAVEL

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

我该怎么做。??

3 个答案:

答案 0 :(得分:3)

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

修改

嘿蓓蕾!我在jenssenger docs上创立了这个:

将项添加到数组中。

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'));

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

为什么不改变这样的数据:

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