SoFunction
Updated on 2025-03-09

Instance code for connecting to remote database in Mongodb under PHP

WINDOWS download MongoDB

Go to the official website to download first:/download-center#atlas

1. Create data, logs folders and

Command line command!

 D:\mongodb\bin> mongod --dbpath D:\mongodb\data --logpath=D:\mongodb\logs\ --logappend 
 D:\mongodb\bin>  mongod -dbpath "d:\mongodb\data\db"
D:\mongodb\bin> 
mongod --config "d:\mongodb\"

2. Configuration

dbpath=D:\Program Files\MongoDB\Server\3.2\data #Database pathlogpath=D:\Program Files\MongoDB\Server\3.2\logs\ #Login output file pathlogappend=true #Error log adopts append modejournal=true #Enable log files, enabled by defaultquiet=true #This option can filter out some useless log information. If you need to debug it, please set it to false.port=27017 #Port number Default is27017

3. Set mongo as a service to facilitate future startup

mongod --config "D:\Program Files\MongoDB\Server\3.2\" --install --serviceName "MongoDB" 
net start MongoDB 

PHP connection

$conn = new MongoClient("mongodb://xxx",array('username'=>'username','password'=>'password'));
$db = $conn->test; 
$collection = $db->test; 
$cursor = $collection->find(); 
foreach ($cursor as $id => $value) { 
  echo "$id: "; var_dump($value); echo "<br>";    
} 

Summarize

The above is the example code for connecting to remote databases under PHP introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!