4

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

3 Answers 3

4

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'));
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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.

1 Comment

I cant change the schema... :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.