一:php 连接mogodb

连接MongoDB数据库

$conn = new Mongo();

php连接mongodbphp 衔接mongodb实例 Bootstrap

其他链接办法

//$conn=new Mongo(); #连接本地主机,默认端口.

//$conn=new Mongo(“172.21.15.69″); #连接远程主机

//$conn=new Mongo(“xiaocai.loc:10086″); #连接指定端口远程主机

//$conn=new Mongo(“xiaocai.loc”,array(“replicaSet”=>true)); #负载均衡

//$conn=new Mongo(“xiaocai.loc”,array(“persist”=>”t”)); #持久连接

//$conn=new Mongo(“mongodb://sa:123@localhost”); #带用户名密码

//$conn=new Mongo(“mongodb://localhost:27017,localhost:27018″); #连接多个做事器

//$conn=new Mongo(“mongodb:///tmp/mongo-27017.sock”); #域套接字

//$conn=new Mongo(“mongodb://admin_miss:miss@localhost:27017/test”,array(‘persist’=>’p',”replicaSet”=>true)); #完全

$m = new Mongo(“mongodb://${username}:${password}@localhost”);

二:实例1

> db.ks.find();

{ "_id" : ObjectId("58e4b3e51f4ee43f5fce73b5"), "name" : "ks", "age" : 2015, "sex" : true }

{ "_id" : ObjectId("58e4b5521f4ee43f5fce73b6"), "name" : "ks1", "age" : 2015, "sex" : true }

>

$m = new Mongo("mongodb://root:ks_2017@localhost");

$db = $m->ks;

$col = $db->ks;

$data=$col->find();

foreach ($data as $id => $msg) {

echo $msg["name"] . " ";

echo $msg["age"] . " ";

echo $msg["sex"] . "";

}

$m->close();

?>

三:PHP 压测 mongodb

#ab.sh

ab.sh

#!/bin/bash

mtime=$1

for i in `seq 1 $mtime`

do

echo $i

sleep 1

/usr/bin/ab -n $i -c $i http://192.168.146.146/mongo.php?aid=$i

#mongo.php

#ini_set('default_socket_timeout', -1);

$aid=$_GET["aid"];

#proxy IP ,port

$db_host="192.168.146.146";

$db_port="27017";

$db_user="ab";

$db_pwd="ab";

$mongo_value="$aid".rand(0,1000);

echo $mongo_value;

#short contenct

$mongo=new Mongo();

#select db

$db=$mongo->db_mengsy;

#select table

$collect=$db->coll_mengsy;

#set element

$ele=array($mongo_value=>"$mongo_value");

#insert into table

$collect->insert($ele);

?>

//这里采取默认连接本机的27017端口,当然你也可以连接远程主机如192.168.0.4:27017,如果端口是27017,端口可以省略

$m = new Mongo();

// 选择comedy数据库,如果以前没该数据库会自动创建,也可以用$m->selectDB("comedy");

$db = $m->comedy;

//选择comedy里面的collection凑集,相称于RDBMS里面的表,也-可以利用

$collection = $db->collection;

$db->selectCollection("collection");

//添加一个元素

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

//将$obj 添加到$collection 凑集中

$collection->insert($obj);

//添加另一个元素

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

$collection->insert($obj);

//查询所有的记录

$cursor = $collection->find();

//遍历所有凑集中的文档

foreach ($cursor as $obj)

{

echo $obj["title"] . "\n";

}

//删除所有数据

//$collection->remove();

//删除 name 为hm

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

//断开MongoDB连接

$m->close();

?>

db.coll_mengsy.save({name:"abc", age: 25,area:"gd"});