3

好的,我需要做以下事情

我有 mongo 收集为

array (
  '_id' => new MongoId("50513d8338fc5de706000000"),
  'offers' => 
  array (
    '0' => 
    array (
      'minspend' => '50.00',
      'cashback' => '1.50',
      'percentage' => '0.03',
    ),
    '1' => 
    array (
      'minspend' => '100.00',
      'cashback' => '3.00',
      'percentage' => '0.03',
    ),
  ),
  'percentageTotal' => '0.06',
  'test' => new MongoInt32(1),
)

但可以说我只想更新这部分

array (
        '0' => 
        array (
          'minspend' => '50.00',
          'cashback' => '1.50',
          'percentage' => '0.03',
        ),

在不重新创建该数组中的整个数据集合的情况下更改子数组的该部分的最佳方法是什么。

有没有可能做这样的事情

array (
        '0' => 
        array (
'Offer_id'=> new MongoId(5715671561715),
          'minspend' => '50.00',
          'cashback' => '1.50',
          'percentage' => '0.03',
        ),

)

4

1 回答 1

4

您可以$set与点符号一起使用来指定要更新的数组元素:

$collection->update(
    array("_id" => new MongoId("50513d8338fc5de706000000")), 
    array("$set" => array("offers.0" => 
        array (
            'minspend' => '50.00',
            'cashback' => '1.50',
            'percentage' => '0.03',
        )
    ))
);

offers.0指数组中的第 0 个(= 第一个)元素。如果你想更新第二个,你会使用offers.1作为键。

For your second question, I'm assuming you want to add the MongoId to the sub-document. You can do that the same way, simply by adding 'Offer_id' => new MongoId(), before minspend. This will create a new unique MongoId and add it to the sub-document. If you want to add an existing MongoId instead, use new MongoId("...") and replace the ... with the 24 hexidecimal character long string.

If you already have an Offer_id and only want to change the offer that matches that id, you can use the positional $ syntax:

$collection->update(
    array("_id" => new MongoId("50513d8338fc5de706000000"),
          "offers.Offer_id" => new MongoId("5059637720dfeda164ec0fe7")), 

    array("$set" => array("offers.$" => 
        array (
            'minspend' => '50.00',
            'cashback' => '1.50',
            'percentage' => '0.03',
        )
    ))
); 

You query for the document with the correct _id and additionally for the offers.Offer_id. In the update part of the command, you use offers.$ where $ will automatically match the correct sub-document that contains the Offer_id.

于 2012-09-18T05:35:41.667 回答