<?php
//connect to mongodb,default:127.0.0.1
$dbHost
=
"127.0.0.1"
;
$dbPort
=
"27017"
;
//if there are not any params inside,the mongo link for default port:27017 and default
//host:localhost
$conn
=
new
Mongo(
"$dbHost,$dbPort"
);
//select db
//$db = $conn->blog;//这样写也是对的
$db
=
$conn
->selectDB(
"blog"
);
//select collection
//$collection = $db->users;
$collection
=
$db
->selectCollection(
"users"
);
//insert,在users集合中有三个字段:name,password,email
$name
=
"test"
;
$password
=md5(
"123"
);
$email
=
"test@qq.com"
;
$newDoc
=
array
(
"name"
=>
$name
,
"password"
=>
$password
,
"email"
=>
$email
);
$ret
=
$collection
->insert(
$newDoc
);
//delete
//删除 name:"test"的用户,justOne为true删除第一条,false删除所有name为"test"的用户
$collection
->remove(
array
(
'name'
=>
'test'
),
array
(
"justOne"
=> false));
//update
//将集合中name为"zjw"的更新为"zjw1"
$newdata
=
array
(
'$set'
=>
array
(
"name"
=>
"zjw1"
));
$collection
->update(
array
(
"name"
=>
"zjw"
),
$newdata
,
array
(
"multiple"
=>true));
//find 查询所有的
$cursor
=
$collection
->find();
// iterate cursor to display datas of documents
foreach
(
$cursor
as
$document
) {
echo
$document
[
"name"
] .
"\t"
.
$document
[
"password"
].
"\t"
.
$document
[
"email"
].
"<br/>"
;
}
//find on condition
//条件查询
$query
=
array
(
"name"
=>
"zjw1"
);
$cursor
=
$collection
->find(
$query
);
//在$collectio集合中查找满足$query的文档
while
(
$cursor
->hasNext())
{
var_dump(
$cursor
->getNext());
//返回了数组
}
echo
"<br/>"
;
//findOne 查询一条数据
$zjw1_Cursor
=
$collection
->findOne(
array
(
"name"
=>
"zjw1"
));
echo
$zjw1_Cursor
[
"name"
].
"\t"
.
$zjw1_Cursor
[
"password"
].
"\t"
.
$zjw1_Cursor
[
"email"
].
"<br/>"
;
//list db,列出所有数据库
$dbs
=
$conn
->listDBs();
$dbsInfo
=
$dbs
[
"databases"
];
foreach
(
$dbsInfo
as
$info
) {
echo
$info
[
"name"
].
"<br/>"
;
}
//close mongodb
$conn
->close();
?>