<?php// 拼接连接 URI$uri = 'mongodb://mongouser:thepasswordA1@10.66.187.127:27017/admin';$manager = new MongoDB\\Driver\\Manager($uri);// 准备写入数据$document1 = ['username' => 'lily','age' => 34,'email' => 'lily@qq.com'];// 驱动预处理数据,这里可以看到 MongoDB 的 _id 是驱动生成的$bulk = new MongoDB\\Driver\\BulkWrite;$_id1 = $bulk->insert($document1);$result = $manager->executeBulkWrite('tsdb.table1', $bulk);// 或者根据实际需要使用下面的代码确保数据写入到大多数节点// $writeConcern = new MongoDB\\Driver\\WriteConcern(MongoDB\\Driver\\WriteConcern::MAJORITY, 1000);// $result = $manager->executeBulkWrite('testdb.testcollection', $bulk, $writeConcern);// 查询$filter = ['_id' => $_id1];$query = new MongoDB\\Driver\\Query($filter);$rows = $manager->executeQuery('tsdb.table1', $query); // 也可选择优先从从库读foreach($rows as $r){print_r($r);}
stdClass Object([_id] => MongoDB\\BSON\\ObjectID Object([oid] => 582c001618c90a16363abc31)[username] => lily[age] => 34[email] => lily@qq.com)
<?phprequire_once __DIR__ . "/vendor/autoload.php";// 初始化$mongoClient = new MongoDB\\Client('mongodb://mongouser:thepasswordA1@10.66.187.127:27017/admin');// 使用 demo 库下的 users 集合$collection = $mongoClient->demo->users;// 写入一条数据$insertOneResult = $collection->insertOne(['name' => 'gomez']);printf("Inserted %d document(s)\\n", $insertOneResult->getInsertedCount());var_dump($insertOneResult->getInsertedId());// 查询数据$document = $collection->findOne(['name' => 'gomez']);var_dump($document);
Inserted 1 document(s)object(MongoDB\\BSON\\ObjectID)#11 (1) {["oid"]=>string(24) "57e3bf20bf605714a53e69c1"}object(MongoDB\\Model\\BSONDocument)#16 (1) {["storage":"ArrayObject":private]=>array(2) {["_id"]=>object(MongoDB\\BSON\\ObjectID)#14 (1) {["oid"]=>string(24) "57e3bf20bf605714a53e69c1"}["name"]=>string(5) "gomez"}}
本页内容是否解决了您的问题?