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?
source to share
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'));
source to share
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.
source to share