php 操作 mongodb

释放双眼,带上耳机,听听看~!

一、在php中添加mongodb扩展:

点击下载扩展库

解压获取一个dll重命名为php_mongo.dll,将其放到php安装目录下的ext文件夹下,然后在php.ini中添加:

二、在mongo启动的前提下,php操作mongodb


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
1<?php
2   //connect to mongodb,default:127.0.0.1
3   $dbHost="127.0.0.1";
4   $dbPort="27017";
5   //if there are not any params inside,the mongo link for default port:27017 and default
6   //host:localhost
7  
8   $conn = new Mongo("$dbHost,$dbPort");
9  
10 
11  //select db
12  //$db = $conn->blog;//这样写也是对的
13  $db = $conn->selectDB("blog");
14 
15 
16  //select collection
17  //$collection = $db->users;
18  $collection = $db->selectCollection("users");
19 
20  //insert,在users集合中有三个字段:name,password,email
21  $name="test";
22  $password=md5("123");
23  $email="test@qq.com";
24 
25   $newDoc = array(
26      "name" => $name,
27      "password" => $password,
28      "email" => $email
29  );
30  $ret = $collection->insert($newDoc);
31 
32 
33 
34 
35 
36  //delete
37  //删除 name:"test"的用户,justOne为true删除第一条,false删除所有name为"test"的用户
38  $collection->remove(array('name'=>'test'), array("justOne" => false));
39 
40 
41 
42 
43 
44  //update
45  //将集合中name为"zjw"的更新为"zjw1"
46  $newdata = array('$set' => array("name" => "zjw1"));
47  $collection->update(array("name" => "zjw"), $newdata,array("multiple"=>true));
48 
49 
50 
51 
52  //find   查询所有的
53  $cursor = $collection->find();
54  // iterate cursor to display datas of documents
55  foreach ($cursor as $document) {
56      echo $document["name"] . "\t".$document["password"]."\t".$document["email"]."<br/>";
57  }
58 
59  //find on condition
60  //条件查询
61  $query = array("name"=>"zjw1");
62        $cursor = $collection->find($query); //在$collectio集合中查找满足$query的文档
63        while($cursor->hasNext())
64        {
65          var_dump($cursor->getNext()); //返回了数组
66        }
67  echo "<br/>";
68 
69  //findOne 查询一条数据
70  $zjw1_Cursor = $collection->findOne(array("name"=>"zjw1"));
71 
72  echo $zjw1_Cursor["name"]."\t".$zjw1_Cursor["password"]."\t".$zjw1_Cursor["email"]."<br/>";
73 
74 
75  //list db,列出所有数据库
76  $dbs = $conn->listDBs();
77  $dbsInfo= $dbs["databases"];
78  foreach ($dbsInfo as $info) {
79      echo $info["name"]."<br/>";
80  }
81
82 
83 
84  //close mongodb
85  $conn->close();
86?>
87

给TA打赏
共{{data.count}}人
人已打赏
安全技术

spring cache

2022-1-11 12:36:11

安全经验

如何写一个RPC框架(三):服务注册与服务发现

2021-11-28 16:36:11

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索