MongoDb Update only one value from an array

I have a collection in mongodb that looks like this.

"_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")

      

I only want to update one value in the color array . But when I try to update the array, it removes all values ​​from the color array and replaces it with the new value. Here is the code. ( I AM A USE OF MENGODBA JESSENGER PASSAGE FOR LARAVEL )

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

      

How should I do it?

+3


source to share


3 answers


What you want to do is either change your schema as a {key: value} pair and then follow this tutorial to help you figure out your problem. OR you can get all the values ​​from an array of colors and replace with a new value, then update your document (I wouldn't go for that because it's a dirty approach!).

EDIT

Hey Bud! I based this, on the jenssenger docs:


Click

Add items to the array.

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

      



If you don't want to duplicate elements, set the third parameter to true:

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

      


Retractable

Remove an element from an array.

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

      

+3


source


You need to use the operator $set

. Not sure how it was done in Jessing Mongod, but it could be something like:



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

      

0


source


Why not change your details like this:

"_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")

      

then you can update the element by id.

0


source







All Articles