您可以通过使用按位置排列的数组元素功能来做到这一点。在 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"
}
}