简体   繁体   中英

PHP mongodb update on nested array with multiple conditions

I've thoroughly searched on the internet for this but haven't found a solution.

Problem : I want to update the quantity in this document. Criteria - itemId=126260, accessDays=30

`{ "_id" : ObjectId("547acfa95ca86bec2e000029"), "session_id" : "1111", "email" : "aasdasda@sdfsd.com", "isProcessed" : 0, "couponApplied" : "", "countryId" : 2, "items" : [ { "itemId" : 126260, "batchId" : 102970, "accessDays" : null, "quantity" : 2 }, { "itemId" : 126260, "batchId" : null, "accessDays" : 30, "quantity" : 2 } ] }`

I am trying to do this using PHP :

`$condition = array( "session_id"=>'1111', 'items.itemId'=>126260, 'items.accessDays'=>30);
$new_values = array( '$set' => array("items.$.quantity" => 10) );

$cart_coll->update($condition, $new_values);`

But when I run this code, it updates the first nested object instead of the second.

What am I doing wrong here ? Does mongodb not consider multiple conditions in nested objects ?

You need to use $elemMatch to get the array marker to be in the right place. So your $query becomes

$condition = array( "session_id"=>'1111',
"items" => array(
'$elemMatch'=>array("itemId"=>126260, 'accessDays'=>30)));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM