如何在没有$ pull或$ pop的情况下更新数组中的第n个元素?

时间:2012-04-22 07:59:09

标签: mongodb mongodb-.net-driver mongodb-php mongodb-java mongodb-ruby

如何更新数组内第n个位置元素的值?

我想更新category_id的索引2。

一种解决方案是($pop$pull)和$addToSet

还有其他解决方案吗?

Array ( [_id] => MongoId Object ( [$id] => 4f93ae990c211da128000004 ) 
        [name] => UnderWater Photography Tips 
        [category_id] => Array ( 
                    [0] => MongoId Object ( [$id] => 4f93a5050c211da328000001 ) 
                    [1] => MongoId Object ( [$id] => 4f93a8860c211da128000003 ) 
                    [2] => ) 
        [user_id] => MongoId Object ( [$id] => 4f92565a0c211dd706000001 ) ) 

1 个答案:

答案 0 :(得分:3)

您可以使用the array element by position functionality执行此操作。在PHP中,这看起来像是在做:

$c->update(
    array( '_id' => new MongoID( '4f93ae990c211da128000004' ) ),
    array( '$set' => array(
        'category_id.2' => new MongoID( '4f93a5050c211da328009999' )
    ))
);

在shell上,您将运行:

db.arraytest.update(
    { _id: ObjectId( '4f93ae990c211da128000004' ) },
    { $set: { 'category_id.2' : ObjectId( '4f93a5050c211da328009900' ) } }
);

当我执行以下脚本时,它会准确显示发生的情况:

<?php
$m = new Mongo();
$c = $m->demo->arraytest;

$c->drop();
$c->insert( array(
    '_id' => new MongoID( '4f93ae990c211da128000004' ),
    'name' => 'Underwater',
    'category_id' => array(
        new MongoID( '4f93a5050c211da328000001' ),
        new MongoID( '4f93a5050c211da328000002' ),
        new MongoID( '4f93a5050c211da328000003' ),
        new MongoID( '4f93a5050c211da328000004' ),
    ),
    'user_id' => new MongoID( '4f92565a0c211dd706000001' )
) );

$c->update(
    array( '_id' => new MongoID( '4f93ae990c211da128000004' ) ),
    array( '$set' => array(
        'category_id.2' => new MongoID( '4f93a5050c211da328009999' )
    ))
);

var_dump( $c->findOne( array( '_id' => new MongoID( '4f93ae990c211da128000004' ) ) ) );

现在运行它:

$ php test.php
array(4) {
  ["_id"]=>
  object(MongoId)#6 (1) {
    ["$id"]=>
    string(24) "4f93ae990c211da128000004"
  }
  ["name"]=>
  string(10) "Underwater"
  ["category_id"]=>
  array(4) {
    [0]=>
    object(MongoId)#5 (1) {
      ["$id"]=>
      string(24) "4f93a5050c211da328000001"
    }
    [1]=>
    object(MongoId)#4 (1) {
      ["$id"]=>
      string(24) "4f93a5050c211da328000002"
    }
    [2]=>
    object(MongoId)#11 (1) {
      ["$id"]=>
      string(24) "4f93a5050c211da328009999"
    }
    [3]=>
    object(MongoId)#10 (1) {
      ["$id"]=>
      string(24) "4f93a5050c211da328000004"
    }
  }
  ["user_id"]=>
  object(MongoId)#12 (1) {
    ["$id"]=>
    string(24) "4f92565a0c211dd706000001"
  }
}