Reputation: 251
I'm making a shopping cart in MongoDB and I want to update the quantity field if the user adds a product that's already added.
This is my document:
{
"_id" : "mzipdNS2Xyw-IqV085KrBe5RZucp9M_KqDSYjPinq20",
"products" : [
{
"productId" : "27122",
"quantity" : NumberLong(1),
"displayPrice" : "€ 599.00",
"price" : NumberLong(599),
"name" : "APPLE IPHONE 5S 16GB SPACE GRAY"
}
]
}
I'm running the following code to update my document, but it's not working, can anyone assist me?
$collection->update(array("_id" => $userId, array("products" => array("productId" => $productId))),
array('$set' => array("quantity" => $newQuantity
))
);
Upvotes: 2
Views: 175
Reputation: 3573
In order to update the correct item in the products array you'll have to use the positional $ operator.
$collection->update(
array(
"_id" => $userId,
"products.productId" => $productId,
),
array('$set' => array("products.$.quantity" => $newQuantity))
);
Upvotes: 1