2

I have a deeply nested PHP array which I saved as a document in Mongo and ended up with this structure:

{ 
"_id" : "...", 
"categ1" : { 
    "aaa" : 112.6736, 
    "bbb" : 83.9137, 
    "ccc" : 80.3322,
     .....
    }, 
"categ2" : { 
    "xxx" : 1, 
    "yyy" : 22, 
    "zzz" : 7,
    "subcateg" : {
         "sub1" : 1,
         "sub2" : 22
         }
    } 
}

Now, I have another array with a similar structure and I would like to increase the values of the record, by the values of the modifier array:

$modifier=array(
    'categ1' => array(
          'aaa' => 3,
          'bbb' => -1,
          'mmm' => 11
        ),
     'categ2' => array(
           'yyy' => -2,
           'subcateg' => array(
                 'sub1' => -1
            )
        )
     );

How can I increase the values inside the document by the values of the $modifier all at once, in a single query, and without loading the entire document ?

I've looked around the web but couldn't find any info on this. Also, i'm pretty newbie at Mongo. Thanks

2
  • What you meant by increase the values of the record? Did you mean replace by modifier Commented Dec 22, 2014 at 18:56
  • what i mean is: i need to increase the values of aaa, bbb, xxx by those specified in modifier[aaa,bbb....] Commented Dec 22, 2014 at 18:57

1 Answer 1

1

You can get your $modifier array to look like this:

$modifier = array(
  'categ1.aaa' => 3,
  'categ1.bbb' => -1,
  'categ1.mmm' => 11,
  'categ2.yyy' => -2,
  'categ2.subcateg.sub1' => -1
)

Link for how to get that.

Then you should be able to simply use:

$col->update(
    array("_id" => "..."),
    array('$inc' => $modifier),
    array("upsert" => true)
);
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.