簡體   English   中英

在 PHP 7.1.6 中使用 MongoDB\Driver 檢查 mongodb 中是否存在集合

[英]Check if collection exists in mongodb using MongoDB\Driver in PHP 7.1.6

我一直在尋找答案,但沒有任何結果。 我需要使用 PHP 7.1.6 中的 MongoDB\Driver 檢查我的 mongodatbase 中是否存在集合。 有誰知道該怎么做? 謝謝。

我做了這個方法來驗證是否存在集合必須傳遞名稱,如果不存在則返回0,如果存在則返回1

public function verifyCollection($name){

  $bd = $this->conexion->mongo(); 
  $data = $bd->listCollections([
   'filter' => [
       'name' => $name,
    ], 
 ]);

$exist = 0;
  foreach ($data as $collectionInfo) {
    $exist = 1;
   }

    return $exist;
 } 

使用db.getCollectionNames()然后使用indexOf() () 測試您尋找的集合是否存在,例如

 idx = db.getCollectionNames().indexOf("myColl");

如果 idx = -1,則myColl不存在。 perl 中的等價物是

my @collections = $database->collection_names;

然后你可以使用 smartmatch 或 grep 或任何你喜歡的方法來掃描集合列表。

您可以使用listCollections()只需記住它返回一個對象而不是數組。 在下面的代碼中,$collectionNames 是一個僅包含名稱的數組。

$collections = $database->listCollections();
$collectionNames = [];
foreach ($collections as $collection) {
  $collectionNames[] = $collection->getName();
}

然后像這樣檢查它:

$exists = in_array('some_collection', $collectionNames);

這對我有用。 基本上你使用listCollections()函數,但要弄清楚如何在 php-extension 中正確使用它並不容易(感謝@John56 在這個線程中的回答)。 $managerMongoDB\Driver\Manager類。 希望它可以幫助您節省一些時間:)

$command = new Command(['listCollections' => 1, 'filter' => ['name' => 'collection-name']]);
$result = $manager->executeCommand('db-name', $command)->toArray();
if (false == empty($result) { whatever ...}

首先在這里創建你的 mongo 對象$mongodb_object然后

$collections = $mongodb_object->getCollectionNames();

collections 變量包含所有集合名稱作為數組返回數組示例如下

[0] => collection_name1
[1] => collection_name2
[2] => collection_name3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM