使用 PHP 创建 MongoDB 数据 (创建)
进行MongoDB的操作验证
sudo systemctl status mongod
在Ubuntu 20.04 中进行库的安装。
sudo apt install pkg-config
sudo apt install php-dev
sudo pecl install mongodb
将内容添加到设置文件中
(省略)
extension=mongodb.so
(省略)
composer require vlucas/phpdotenv
composer require mongodb/mongodb
#! /usr/bin/php
<?php
// --------------------------------------------------------------------
/*
mongo_create.php
Jun/08/2019
*/
// --------------------------------------------------------------------
function dict_append_proc ($dict_aa,$id,$name,$population,$date_mod)
{
$dict_unit = array ();
$dict_unit['name'] = $name;
$dict_unit['population'] = $population;
$dict_unit['date_mod'] = $date_mod;
$dict_aa[(string)$id]= $dict_unit;
return $dict_aa;
}
// --------------------------------------------------------------------
function data_prepare_proc ()
{
$dict_aa = array ();
$dict_aa = dict_append_proc ($dict_aa,'t1161','さいたま',72136,'2002-5-18');
$dict_aa = dict_append_proc ($dict_aa,'t1162','所沢',41378,'2002-9-12');
$dict_aa = dict_append_proc ($dict_aa,'t1163','越谷',59213,'2002-4-1');
$dict_aa = dict_append_proc ($dict_aa,'t1164','久喜',96329,'2002-10-29');
$dict_aa = dict_append_proc ($dict_aa,'t1165','熊谷',35736,'2002-7-14');
$dict_aa = dict_append_proc ($dict_aa,'t1166','秩父',24683,'2002-6-12');
$dict_aa = dict_append_proc ($dict_aa,'t1167','川越',82197,'2002-2-17');
$dict_aa = dict_append_proc ($dict_aa,'t1168','和光',18572,'2002-3-24');
$dict_aa = dict_append_proc ($dict_aa,'t1169','新座',59461,'2002-7-8');
return $dict_aa;
}
// --------------------------------------------------------------------
fputs (STDERR,"*** 開始 ***\n");
$dict_aa = data_prepare_proc ();
require_once './vendor/autoload.php';
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();
//
$user = $_ENV['user'];
$password = $_ENV['password'];
$str_connect = "mongodb://" . $user . ":" . $password . "@localhost:27017";
$manager = new MongoDB\Driver\Manager($str_connect);
$manager->executeCommand('city', new \MongoDB\Driver\Command(["drop" => "saitama"]));
$bulk = new MongoDB\Driver\BulkWrite;
foreach ($dict_aa as $key => $value)
{
$bulk->insert(['key' => $key, 'name' => $value["name"],
'population' => $value['population'], 'date_mod' => $value['date_mod']]);
}
$manager->executeBulkWrite('city.saitama', $bulk);
fputs (STDERR,"*** 終了 ***\n");
// --------------------------------------------------------------------
?>
user = '******'
password = '******'
执行命令
./mongo_create.php
我在下一个版本中进行了确认。
$ php --version
PHP 8.0.8 (cli) (built: Oct 26 2021 11:42:42) ( NTS )
使用mongosh确认数据
$ mongosh -u scott -p tiger123
(省略)
test> use city
switched to db city
city> db.saitama.find()
[
{
_id: ObjectId("61fcc4838ad033156d4d33c2"),
key: 't1161',
name: 'さいたま',
population: 72136,
date_mod: '2002-5-18'
},
{
_id: ObjectId("61fcc4838ad033156d4d33c3"),
key: 't1162',
name: '所沢',
population: 41378,
date_mod: '2002-9-12'
},
(省略)
city>exit