Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDb Update only one value from array

I have a collection in mongodb which 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 want to update only one value in the array color But when i try to update the array it removes all the values from the color array and replaces it by the new value. Here is the code. (I AM USING JESSENGER MONGODB PACKAGE FOR LARAVEL)

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

How should i do it.??

like image 728
Sameer Shaikh Avatar asked Sep 17 '25 00:09

Sameer Shaikh


1 Answers

What you wanna do is, either change your schema as {key: value} pair and then follow this tutorial, that will help you to sort out your problem. OR you can get all the values from color array and replace with new value and then update your document (I would not go for it coz it is a dirty approach!).

EDIT

Hey Bud! I founded this, on jenssenger docs:


Push

Add an items to an 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 duplicate items, set the third parameter to true:

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

Pull

Remove an item 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'));
like image 120
Gaurav Dave Avatar answered Sep 18 '25 17:09

Gaurav Dave