1024programmer Java PHP connection to MongoDB example

PHP connection to MongoDB example

Example of PHP connection to MongoDB:

<?php

//The default port 27017 is used to connect to the local machine. Of course, you can also connect to a remote host such as 192.168.0.4:27017. If the port is 27017, the port Can be omitted

$m = new Mongo();

//Select comedy database. If the database has not been created before, it will be automatically created. You can also use $m->selectDB(“comedy”);

$db = $m->comedy;

//Select the collection in comedy, which is equivalent to the table in RDBMS, and can also be used

$collection = $db->collection;

$db->selectCollection(“collection”);

//Add an element

$obj = array( “title” => “Calvin and Hobbes-“.date('i:s'), “author” => “Bill Watterson” );

//Add $obj to the $collection collection

$collection->insert($obj);

//Add another element

$obj = array( “title” => “XKCD-“.date('i:s'), “online” => true );

$collection->insert($obj);

//Query all records

$cursor = $collection->find();

//Traverse the documents in all collections

foreach ($cursor as $obj)

{

echo $obj[“title”] . “\n”;

}

//Delete all data

$collection->remove();

//Delete name as hm

$collection->remove(array('name'=>'hm'));

//Disconnect MongoDB

$m->close();

?>

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/php-connection-to-mongodb-example-2/

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索