Home > Backend Development > PHP Tutorial > Detailed example of how to connect Mongodb to a remote database under PHP

Detailed example of how to connect Mongodb to a remote database under PHP

巴扎黑
Release: 2023-03-15 17:08:02
Original
1654 people have browsed it

这篇文章主要介绍了PHP下 Mongodb 连接远程数据库的实例代码,需要的朋友可以参考下

WINDOWS 下装MongoDB

先去官网下载  :https://www.mongodb.com/download-center#atlas

1、在mongodb的文件夹下创建 data、logs 文件夹 和mongo.conf

命令行命令!


 D:\mongodb\bin> mongod --dbpath D:\mongodb\data --logpath=D:\mongodb\logs\mongodb.log --logappend 
 D:\mongodb\bin>  mongod -dbpath "d:\mongodb\data\db"
D:\mongodb\bin> 
mongod --config "d:\mongodb\mongo.conf"
Copy after login

2、配置mongo.conf


dbpath=D:\Program Files\MongoDB\Server\3.2\data #数据库路径 
logpath=D:\Program Files\MongoDB\Server\3.2\logs\mongo.log #日志输出文件路径 
logappend=true #错误日志采用追加模式 
journal=true #启用日志文件,默认启用 
quiet=true #这个选项可以过滤掉一些无用的日志信息,若需要调试使用请设置为false 
port=27017 #端口号 默认为27017
Copy after login

3、将mongo设为服务,方便以后启动


mongod --config "D:\Program Files\MongoDB\Server\3.2\mongo.conf" --install --serviceName "MongoDB" 
net start MongoDB
Copy after login

PHP连接


$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>";    
}
Copy after login

The above is the detailed content of Detailed example of how to connect Mongodb to a remote database under PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template