我正试图使用堆栈溢出中的建议在本地机器上使用MongoDB。我在Windows10上使用XAMPP,php版本8.01,MongoDB扩展为1.9.0。
这是一个非常基本的脚本,它连接到MongoDB并尝试使用其中一个数据库。
但我仍然收到这个警告:
Connection to database successfully
Warning: Undefined property: MongoDBDriverManager::$aws_inventories in C:xampphtdocsmongo_connect.php on line 8
这是我的代码:
<?php
require 'C:xampphtdocsvendorautoload.php'; // include Composer's autoloader
$DB_CONNECTION_STRING="mongodb://localhost:27017";
// connect to mongodb
$m = new MongoDBDriverManager( $DB_CONNECTION_STRING );
echo "Connection to database successfully";
// select a database
$db = $m->aws_inventories;
?>
如何摆脱警告并正确连接到数据库?
首先,您试图访问MongoDBDriverManager
类对象中不存在的属性。
第二,$db = $m->aws_inventories;
与MongoDBClient
库协同工作。
以下是获取集合列表或查找所有/特定文档或插入/批量插入、更新文档或执行不同查询的几个示例
获取所有aws_inventors:集合
try {
$manager = new MongoDBDriverManager('mongodb://localhost:27017');
$command = new MongoDBDriverCommand(["listCollections" => 1]);
$cursor = $manager->executeCommand("aws_inventories", $command);
// list of all collections in aws_inventories
$collections = $cursor->toArray();
var_dump($collections);
} catch (MongoDBDriverExceptionException $e) {
}
从集合中获取所有文档:
try {
$manager = new MongoDBDriverManager('mongodb://localhost:27017');
// setting options and filter
$filter = [];
$options = [];
/*
// or to find specific documents based on a condition and limit records
$filter = [
'service' => 'ec2',
'instance' => 'co',
'type' => 'c5',
'vCPU' => [
'$gt' => 2
]
];
$options = [
'limit' => 10,
'maxTimeMS' => 1000, // to limit the execution time of a query
'sort' => [
'vCPU' => -1
]
];
*/
// constructing the query
$query = new MongoDBDriverQuery($filter, $options);
$cursor = $manager->executeQuery('aws_inventories.test', $query);
foreach ($cursor as $document) {
var_dump($document);
}
} catch (MongoDBDriverExceptionException $e) {
}
执行不同查询:
try {
$manager = new MongoDBDriverManager('mongodb://localhost:27017');
$query = [
'size' => '2xlarge'
];
$command = new MongoDBDriverCommand([
'distinct' => 'test', // Collection name
'key' => 'instance', // field for which we want to get distinct values
'query' => $query // criteria to filter documents
]);
$cursor = $manager->executeCommand("aws_inventories", $command);
// to get distinct values as array
$instances = current($cursor->toArray())->values;
var_dump($instances);
} catch (MongoDBDriverExceptionException $e) {
}
插入单个/多个文档:
try {
$manager = new MongoDBDriverManager('mongodb://localhost:27017');
$bulk = new MongoDBDriverBulkWrite;
$bulk->insert([
'service' => 'ec2',
'instance' => 'co',
'type' => 'c5',
'size' => 'large',
'model' => 'c5.large',
'vCPU' => 2,
'memory' => 4,
'storage' => 'ebs-only',
'network_bandwidth' => 10,
'ebs_bandwidth' => 4750
]);
$bulk->insert([
'service' => 'ec2',
'instance' => 'gp',
'type' => 't3',
'size' => 'nano',
'model' => 't3.nano',
'vCPU' => 2,
'memory' => 0.5,
'storage' => 'ebs-only',
'network_bandwidth' => 5
]);
$result = $manager->executeBulkWrite('aws_inventories.test', $bulk);
} catch (MongoDBDriverExceptionException $e) {
}
更新现有文档:(取自executeUpdate示例(
try {
$manager = new MongoDBDriverManager('mongodb://localhost:27017');
$criteria = [
'service' => 'ec2',
'type' => 'c5'
];
$document = [
'$set' => [
'features' => [
'Powered by the AWS Nitro System, a combination of dedicated hardware and lightweight hypervisor'
]
]
];
$updateOptions = array(
'multi' => true, // false - to update only first matching document, true - update all matching documents
'upsert' => 0
);
$writeConcern = new MongoDBDriverWriteConcern(MongoDBDriverWriteConcern::MAJORITY, 100);
$result = $manager->executeUpdate('aws_inventories.test', $criteria, $document, $updateOptions, $writeConcern);
printf("Updated %d document(s)n", $result->getModifiedCount());
printf("Matched %d document(s)n", $result->getMatchedCount());
printf("Upserted documents: %dn", $result->getUpsertedCount());
foreach ($result->getUpsertedIds() as $index => $id) {
printf("upsertedId[%d]: ", $index);
var_dump($id);
}
/* If the WriteConcern could not be fulfilled */
if ($writeConcernError = $result->getWriteConcernError()) {
printf("%s (%d): %sn", $error->getMessage(), $error->getCode(), var_export($error->getInfo(), true));
}
/* If the write could not happen at all */
foreach ($result->getWriteErrors() as $writeError) {
printf("%s (%d)n", $error->getMessage(), $error->getCode());
}
} catch (MongoDBDriverExceptionException $e) {
}
$m->aws_inventories
这看起来像是旧的/不推荐使用的方法。你能试着遵循这个教程吗?
https://zetcode.com/db/mongodbphp/
<?php
try {
$mng = new MongoDBDriverManager("mongodb://localhost:27017");
$stats = new MongoDBDriverCommand(["dbstats" => 1]);
$res = $mng->executeCommand("aws_inventories", $stats);
$stats = current($res->toArray());
print_r($stats);
} catch (MongoDBDriverExceptionException $e) {
$filename = basename(__FILE__);
echo "The $filename script has experienced an error.n";
echo "It failed with the following exception:n";
echo "Exception:", $e->getMessage(), "n";
echo "In file:", $e->getFile(), "n";
echo "On line:", $e->getLine(), "n";
}
?>
此示例改编自官方文档https://www.php.net/manual/en/mongodb-driver-manager.executequery.php
<?php
require 'vendor/autoload.php';
$manager = new MongoDBDriverManager("mongodb://localhost:27017");
$db = 'test_database';
$col = 'mycol';
$namespace = $db.'.'.$col;
// insert data
$bulk = new MongoDBDriverBulkWrite;
$bulk->insert(['x' => 1]);
$bulk->insert(['x' => 2]);
$bulk->insert(['x' => 3]);
$manager->executeBulkWrite($namespace, $bulk);
// query
$query = new MongoDBDriverQuery(['x' => ['$gt' => 1]], []);
$cursor = $manager->executeQuery($namespace, $query);
foreach ($cursor as $document) {
var_dump($document);
}
正如文档所示,MongoDB \Driver\Manager是一个通用抽象,用于管理任何类型的MongoDB连接(独立服务器、副本集或分片集群(,因此对于独立服务器上的简单CRUD来说,这些方法看起来有点太复杂了。
如果你只想连接到一个独立的服务器,你可能需要检查MongoDB \ Client。以下是做完全相同事情的代码:
<?php
require 'vendor/autoload.php';
$client = new MongoDBClient("mongodb://localhost:27017");
$col = $client->test_database->mycol;
// insert data
$col->insertMany([
['x' => 1],
['x' => 2],
['x' => 3],
]);
// query
$docs = $col->find(['x' => ['$gt' => 1]]);
foreach ($docs as $document) {
var_dump($document);
}