mongodb 命令行下及php中insert数据详解
前面说了到数据库连接操作,请参考:mongodb添加用户及权限设置详解
对数据库的操作:请参考:mongodb数据库操作详解--创建,切换,删除
下面说一下,数据库表的插入操作
1,命令行下的insert操作
>usetest;#切换到test数据库 switchedtodbtest >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数据
<?php //$mongo=newMongo("mongodb://192.168.10.202:27017");//链接远程数据库 $mongo=newMongo();//链接远程数据库 $curDB=$mongo->selectDB("test");//选择要操作的数据库,如果不存在,则自动创建 $collection=$curDB->selectCollection("test");//选中一个集合(理解为table),如果不存在,则自动创建 //$collection->drop();//清空集合testCollection $count=$collection->count();//查看集合中的数据量 echo"insert前集合中有[".$count."]条数据<Br>";//这里的二条数据主命令行下插入的。 echo"<br>**********mongodbphpinsert插入*************<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]条数据
**********mongodbphpinsert插入*************
bool(true)
新增对象的id:53c908c87f8b9ad7218b4568
Array([n]=>0[connectionId]=>4[err]=>[ok]=>1)
新增对象的id:53c908c87f8b9ad7218b4569
insert后集合中有[4]条数据