
- PHP & MongoDB 教程
- PHP & MongoDB - 主頁
- PHP & MongoDB - 概覽
- PHP & MongoDB - 環境設定
- PHP & MongoDB 示例
- PHP & MongoDB - 連線資料庫
- PHP & MongoDB - 顯示資料庫
- PHP & MongoDB - 刪除資料庫
- PHP & MongoDB - 建立集合
- PHP & MongoDB - 刪除集合
- PHP & MongoDB - 顯示集合
- PHP & MongoDB - 插入文件
- PHP & MongoDB - 選擇文件
- PHP & MongoDB - 更新文件
- PHP & MongoDB - 刪除文件
- PHP & MongoDB - 巢狀文件
- PHP & MongoDB - 錯誤處理
- PHP & MongoDB - 限制記錄
- PHP & MongoDB - 排序記錄
- PHP & MongoDB 實用資源
- PHP & MongoDB - 快速指南
- PHP & MongoDB - 實用資源
- PHP & MongoDB - 討論
PHP & MongoDB - 插入巢狀文件
進行任何操作的第一步是建立 Manager 例項。
// Connect to MongoDB using Manager Instance $manager = new MongoDB\Driver\Manager("mongodb://:27017");
第二步是編寫並執行一個 bulkWrite 物件,在集合中插入帶巢狀文件的記錄。
// Create a BulkWrite Object $bulk = new MongoDB\Driver\BulkWrite(['ordered' => true]); $bulk->insert(['title' => "MongoDB Overview", 'description' => 'MongoDB is no SQL database', 'by' => 'tutorials point', 'url' => 'https://tutorialspoint.tw', 'comments' => [ ['user' => "user1", 'message' => "My First Comment", 'dateCreated' => "20/2/2020", 'like' => 0], ['user' => "user2", 'message' => "My Second Comment", 'dateCreated' => "20/2/2020", 'like' => 0], ]]); // Execute the commands. $result = $manager->executeBulkWrite('myDb.sampleCollection', $bulk);
示例
請嘗試下面的示例,在 MongoDB 伺服器的集合中插入帶巢狀文件的文件 -
將以下示例複製並貼上為 mongodb_example.php -
<?php try { // connect to mongodb $manager = new MongoDB\Driver\Manager("mongodb://:27017"); $bulk = new MongoDB\Driver\BulkWrite(['ordered' => true]); $bulk->insert(['title' => "MongoDB Overview", 'description' => 'MongoDB is no SQL database', 'by' => 'tutorials point', 'url' => 'https://tutorialspoint.tw', 'comments' => [ ['user' => "user1", 'message' => "My First Comment", 'dateCreated' => "20/2/2020", 'like' => 0], ['user' => "user2", 'message' => "My Second Comment", 'dateCreated' => "20/2/2020", 'like' => 0], ]]); $result = $manager->executeBulkWrite('myDb.sampleCollection', $bulk); printf("Inserted %d document(s).\n", $result->getInsertedCount()); } catch (MongoDB\Driver\Exception\Exception $e) { echo "Exception:", $e->getMessage(), "\n"; } ?>
輸出
訪問部署在 Apache Web 伺服器上的 mongodb_example.php 並驗證輸出。
Inserted 1 document(s).
廣告