1

I have the following document:

{
   "_id": ObjectId("5241f1d79b7e7aed05000000"),
   "description": {
     "nl": "Hallo",
     "en": "Hello"
    },
  "name": "Marc"
}

Now I need to update to update one existing field or add new field to the description. In php I use the update function for Mongo and the following code:

$new_data = array(
    '$set' => array(
    "description" => array(
         "de" => "hallo"
       )
    )
);

What it does it removes all other fields and just insert the "de" field. I tried replacing $set with $push (which I thought was made for this) but no result also $setOnInsert does not do anything.

How can I solve this problem so that I can either add a new field (if it does not exist) or update if it exist.

Thanks

3
  • before updating also add previous record in $new_data in description because think logically you are updating filed Commented Sep 24, 2013 at 21:10
  • That makes sort of sense, but that means in some cases I need to send e.g. 23 extra fields in a post that are not updated. There is no other way? Commented Sep 24, 2013 at 21:20
  • you can add more fields but in your case description is array and you are replacing with other value Commented Sep 24, 2013 at 21:23

1 Answer 1

1

Just make your update like

{$set: {"description.de": "hello"}}

I guess in your code it would be:

$new_data = array(
  '$set' => array(
    "description.de" => "hallo"
  )
);
Sign up to request clarification or add additional context in comments.

Comments

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.