好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

mongodb 命令行下及php中insert数据详解

前面说了到数据库连接操作,请参考: mongodb 添加用户及权限设置详解
对数据库的操作:请参考: mongodb 数据库操作详解--创建,切换,删除
下面说一下,数据库表的插入操作
1,命令行下的insert操作

?

1

2

3

4

5

6

7

8

9

10

11

12

13

> use test ;    #切换到test数据库

switched to db test

 

> document=({ "title" : "linux命令" , "auther" : "tank" });   #定义了一个变量

{ "title" : "linux命令" , "auther" : "tank" }

> db. test .insert(document);     #插入变量

> db. test . find ();       #查看插入的数据

{ "_id" : ObjectId( "53c8fc1cf062ac30ee8b9d2d" ), "title" : "linux命令" , "auther" : "tank" }

 

> db. test .insert({ "title" : "51yip" , "auther" : "tank" });  #直接插入数据

> db. test . find ();       #查看

{ "_id" : ObjectId( "53c8fc1cf062ac30ee8b9d2d" ), "title" : "linux命令" , "auther" : "tank" }

{ "_id" : ObjectId( "53c8f6fff062ac30ee8b9d2e" ), "title" : "51yip" , "auther" : "tank" }

2,利用php扩展insert数据

?

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

<?php

 

//$mongo = new Mongo("mongodb://192.168.10.202:27017"); //链接远程数据库

$mongo = new Mongo();          //链接远程数据库

$curDB = $mongo ->selectDB( "test" );    //选择要操作的数据库,如果不存在,则自动创建

$collection = $curDB ->selectCollection( "test" ); //选中一个集合(理解为 table),如果不存在,则自动创建

//$collection->drop();       //清空集合 testCollection

 

$count = $collection -> count ();     //查看集合中的数据量

echo "insert前集合中有[" . $count . "]条数据<Br>" ;  //这里的二条数据主命令行下插入的。

 

echo "<br>********** mongodb php insert 插入 *************<br>" ;

 

$obj = array ( "title" => "围城" , "auther" => "钱钟书" );

$rel = $collection ->insert( $obj );

var_dump( $rel );         //打印插入后的结果是bool型的

echo "<Br>新增对象的id:" . $obj [ '_id' ]. "<Br>" ;

 

$obj = array ( "title" => "朝发白帝城" , "auther" => "李白" );

$rel = $collection ->insert( $obj , array ( 'safe' =>true)); //safe 表示是否返回操作结果信息,返回的信息为 array

print_r( $rel );         //插入后的结果是数组

echo "<Br>新增对象的id:" . $obj [ '_id' ]. "<Br>" ;;

 

$count = $collection -> count ();     //查看集合中的数据量

echo "insert后集合中有[" . $count . "]条数据<Br>" ;

 

?>

 
运行结果: 
insert前集合中有[2]条数据 
 
********** mongodb php insert 插入 ************* 
bool(true) 
新增对象的id:53c908c87f8b9ad7218b4568 
Array ( [n] => 0 [connectionId] => 4 [err] => [ok] => 1 ) 
新增对象的id:53c908c87f8b9ad7218b4569 
insert后集合中有[4]条数据 

查看更多关于mongodb 命令行下及php中insert数据详解的详细内容...

  阅读:29次