[英]how to get list of collection {Mongodb} in php using 'new MongoDB\Driver\Manager' driver
[英]How to get collection class object from mongodb/driver/manager in PHP
我正在使用(當前?不確定,php 文檔對我來說非常不透明)方法從 PHP 連接到 MongoDB:
$manager = new MongoDB\Driver\Manager("mongodb://{$user}:{$pwd}@{$url}", array("ssl" => true), array("context" => $ctx));
從那里開始,如果我想寫一些東西,我會執行以下操作:
$bson = MongoDB\BSON\fromJSON($newData);
$value = MongoDB\BSON\toPHP($bson);
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->update(
$filter,
['$set' => $value],
['multi' => false, 'upsert' => $upsert]
);
$results = $manager->executeBulkWrite("$DB.$collection", $bulk);
var_dump($results);
MongoDB PHP 教程上的所有文檔都以 $collection object... 開頭,之后的功能看起來更加用戶友好(getInsertedID... insertOne...find...)
例如:
<?php
$collection = (new MongoDB\Client)->test->users;
$insertManyResult = $collection->insertMany([
[
'username' => 'admin',
'email' => 'admin@example.com',
'name' => 'Admin User',
],
[
'username' => 'test',
'email' => 'test@example.com',
'name' => 'Test User',
],
]);
printf("Inserted %d document(s)\n", $insertManyResult->getInsertedCount());
var_dump($insertManyResult->getInsertedIds());
我不清楚他們實際上是如何連接到數據庫的......我將如何 go 從$manager
連接到$collection
?
在 MongoDB PHP 文檔頁面上,它說“您可以直接使用驅動程序的MongoDB\Driver\Manager類構造 collections”。 不幸的是,在結果頁面上的搜索不包括“收藏”這個詞,而不是作為用戶貢獻注釋中的旁注。
在 MongoDB PHP 參考頁面的其他地方,我看不到 MongoDB\Manager class 的描述。
那么,如何訪問MongoDB\Collection class中的許多功能?
我無法從 Manager class 中獲取集合,但是,我能夠使用 bulkWrite class 以安全的方式執行插入(我相信)。 我希望相同的模式也適用於讀取和更新。
那些在我之后來到這里的人的代碼片段:
//echo "Specify the cert...";
$SSL_DIR = ".";
$SSL_FILE = "XXXXXX.pem";
$ctx = stream_context_create(array(
"ssl" => array(
"cafile" => $SSL_DIR . "/" . $SSL_FILE,
))
);
//echo "Done\n";
// echo "Creating manager...";
$manager = new MongoDB\Driver\Manager("mongodb://{$user}:{$pwd}@{$url}", array("ssl" => true), array("context" => $ctx));
// echo "Done!\n";
// echo "Making BSON...";
$bson = MongoDB\BSON\fromJSON($newData);
// echo "Done!\nMaking Value...";
$value = MongoDB\BSON\toPHP($bson);
$value->_id = (string) new MongoDB\BSON\ObjectID;
// echo "Done!\nMaking Bulk...";
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert($value);
// echo "Done!\nExecuting Bulk Write";
$results = $manager->executeBulkWrite("$db.$collection", $bulk);
if($results->getInsertedCount()==1) {
echo $value->_id;
} else {
echo $results->getWriteErrors();
}
// echo "Done!\n";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.