mongodb $inc 数组中的一个字段 [英] mongodb $inc a field inside an array

查看:70
本文介绍了mongodb $inc 数组中的一个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数组结构

Array
(
    [_id] => MongoId Object
        (
            [$id] => 538978ce8ead0ec1048b456c
        )

    [cartId] => 98374319ff71dbc3a84b842b7a443cf7
    [products] => Array
        (
            [0] => Array
                (
                    [productId] => 100343
                    [quantity] => 17
                    [name] => a
                )

            [1] => Array
                (
                    [productId] => 100344
                    [quantity] => 3
                    [name] => ab
                )

            [2] => Array
                (
                    [productId] => 100345
                    [quantity] => 1
                    [name] => abc
                )

        )

我在根据 productId 增加产品数量时遇到问题

And i'm having problems to increment the quantity of the products based on the productId

我现在使用位置但我没有关于id的参考

 $oCartsCollection->update(array('cartId'=>'98374319ff71dbc3a84b842b7a443cf7'), array('$inc' => array('products.0.quantity'=>1)));

推荐答案

您需要做的是添加到您的查询以从您的数组中选择和元素,然后使用 位置 $ 运算符以匹配该位置:

What you need to do is add to your query to select and element from your array and then use the positional $ operator in order to match that position:

$oCartsCollection->update(
    array(
        'cartId'=>'98374319ff71dbc3a84b842b7a443cf7',
        'products.productId' => 100343
     ), 
    array('$inc' => array('products.$.quantity'=>1)));

在这种情况下,点"符号方法适用于访问 productId 元素.要匹配多个字段,请使用 $elemMatch 代替

The "dot" notation method is fine for accessing the productId element in this case. For multiple fields to match use $elemMatch instead

$oCartsCollection->update(
    array(
        'cartId'=>'98374319ff71dbc3a84b842b7a443cf7',
        'products' => array(
            '$elemMatch' => array(
                'productId' => 100343,
                'name' => 'a'
            )
        )
     ), 
    array('$inc' => array('products.$.quantity'=>1)));

这篇关于mongodb $inc 数组中的一个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆