gpt4 book ai didi

php - 根据 PHP 中的 2 个条件更新 MongoDB 中的数量

转载 作者:可可西里 更新时间:2023-11-01 10:43:21 25 4
gpt4 key购买 nike

我在 MongoDB 中制作了一个购物车,如果用户添加了一个已经添加的产品,我想更新数量字段。

这是我的文档:

{
"_id" : "mzipdNS2Xyw-IqV085KrBe5RZucp9M_KqDSYjPinq20",
"products" : [
{
"productId" : "27122",
"quantity" : NumberLong(1),
"displayPrice" : "€ 599.00",
"price" : NumberLong(599),
"name" : "APPLE IPHONE 5S 16GB SPACE GRAY"
}
]
}

我正在运行以下代码来更新我的文档,但它不起作用,有人可以帮助我吗?

$collection->update(array("_id" => $userId, array("products" => array("productId" => $productId))),
array('$set' => array("quantity" => $newQuantity
))
);

最佳答案

为了更新产品数组中的正确项目,您必须使用 positional $ operator .

$collection->update(
array(
"_id" => $userId,
"products.productId" => $productId,
),
array('$set' => array("products.$.quantity" => $newQuantity))
);

关于php - 根据 PHP 中的 2 个条件更新 MongoDB 中的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27905095/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com