Sameer Shaikh
Sameer Shaikh

Reputation: 265

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.??

Upvotes: 4

Views: 5325

Answers (3)

Gaurav Dave
Gaurav Dave

Reputation: 7494

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

Upvotes: 4

I'm 怀朔
I'm 怀朔

Reputation: 41

Why don't change your data 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 element by id.

Upvotes: 0

blubear
blubear

Reputation: 441

You need to use the $set operator. Not sure how it's done in Jessenger Mongodb, but it might be something like:

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

Upvotes: 0

Related Questions