1

How to update value of the nth position element inside an array?

I want to update index 2 of category_id.

One solution is ($pop or $pull) and $addToSet.

Is there any other solution?

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 ) ) 
P K
  • 9,972
  • 12
  • 53
  • 99
  • 2
    Have ypu tried [Array Element by Position](http://www.mongodb.org/display/DOCS/Dot+Notation+%28Reaching+into+Objects%29) as noted in the docs? (nned to scroll down) – DrColossos Apr 22 '12 at 10:22

1 Answers1

3

You can do this by using the array element by position functionality. In PHP, that would look like doing:

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

On the shell, you would run:

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

When I execute the following script, it shows exactly what happens:

<?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' ) ) ) );

Now run it:

$ 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"
  }
}
Derick
  • 35,169
  • 5
  • 76
  • 99