MongoDB:如何使用php-library添加具有增量编号的字段?

时间:2017-09-05 06:12:23

标签: php mongodb

在MongoDB php库的dosc中,有一个Update Many Documents示例,如下所示: docs:https://docs.mongodb.com/php-library/master/tutorial/crud/#insert-many-documents

$collection = (new MongoDB\Client)->test->users;
$collection->drop();

$collection->insertOne(['name' => 'Bob', 'state' => 'ny', 'country' => 'us']);
$collection->insertOne(['name' => 'Alice', 'state' => 'ny']);
$collection->insertOne(['name' => 'Sam', 'state' => 'ny']);
$updateResult = $collection->updateMany(
    ['state' => 'ny'],
    ['$set' => ['country' => 'us']]
);

上面的例子添加了一个具有相同值的字段。 我有一个现有的碰撞,就像这样:

  $categories =[
            ['_id' => ObjectId('xxx'),'category' => 'fruit'],
            ['_id' => ObjectId('xxx'),'category' => 'sport'],
            ['_id' => ObjectId('xxx'),'category' => 'book'],
            ['_id' => ObjectId('xxx'),'category' => 'animal'],
  ];

我将它导入mysql,我想首先在MongoDB中添加一个字段category_id。 该数字是增量的,从1开始,结果如下:

$newCategories =[
        ['_id' => ObjectId('xxx'),'category' => 'fruit','category_id' =>1 ],
        ['_id' => ObjectId('xxx'),'category' => 'sport','category_id' =>2],
        ['_id' => ObjectId('xxx'),'category' => 'book','category_id' =>3],
        ['_id' => ObjectId('xxx'),'category' => 'animal','category_id' =>4],
 ];

如何使用php-library?

0 个答案:

没有答案