当前位置:Gxlcms > mysql > mongodbinsert数据,php扩展insert数据

mongodbinsert数据,php扩展insert数据

时间:2021-07-01 10:21:17 帮助过:32人阅读

前面说了到数据库连接操作,请参考: mongodb 用户 权限 设置 详解 对数据库的操作:请参考: mongodb 数据库创建,切换,删除 下面说一下,数据库表的插入操作 1,命令行下的insert操作 use test; #切换到test数据库switched to db test document=({"title" :

前面说了到数据库连接操作,请参考:mongodb 用户 权限 设置 详解

对数据库的操作:请参考:mongodb 数据库创建,切换,删除

下面说一下,数据库表的插入操作

1,命令行下的insert操作

  1. > use test; #切换到test数据库
  2. switched to db test
  3. > document=({"title" : "linux命令", "auther" : "tank" }); #定义了一个变量
  4. { "title" : "linux命令", "auther" : "tank" }
  5. > db.test.insert(document); #插入变量
  6. > db.test.find(); #查看插入的数据
  7. { "_id" : ObjectId("53c8fc1cf062ac30ee8b9d2d"), "title" : "linux命令", "auther" : "tank" }
  8. > db.test.insert({"title" : "51yip", "auther" : "tank" }); #直接插入数据
  9. > db.test.find(); #查看
  10. { "_id" : ObjectId("53c8fc1cf062ac30ee8b9d2d"), "title" : "linux命令", "auther" : "tank" }
  11. { "_id" : ObjectId("53c8f6fff062ac30ee8b9d2e"), "title" : "51yip", "auther" : "tank" }

2,利用php扩展insert数据

  1. <!--?php
  2. //$mongo = new Mongo("mongodb://192.168.10.202:27017"); //链接远程数据库
  3. $mongo = new Mongo(); //链接远程数据库
  4. $curDB = $mongo--->selectDB("test"); //选择要操作的数据库,如果不存在,则自动创建
  5. $collection = $curDB->selectCollection("test"); //选中一个集合(理解为 table),如果不存在,则自动创建
  6. //$collection->drop(); //清空集合 testCollection
  7. $count = $collection->count(); //查看集合中的数据量
  8. echo "insert前集合中有[".$count."]条数据"; //这里的二条数据主命令行下插入的。
  9. echo "********** mongodb php insert 插入 *************";
  10. $obj = array("title"=>"围城","auther"=>"钱钟书");
  11. $rel = $collection->insert($obj);
  12. var_dump($rel); //打印插入后的结果是bool型的
  13. echo "新增对象的id:".$obj['_id']."";
  14. $obj = array("title"=>"朝发白帝城","auther"=>"李白");
  15. $rel = $collection->insert($obj,array('safe'=>true)); //safe 表示是否返回操作结果信息,返回的信息为 array
  16. print_r($rel); //插入后的结果是数组
  17. echo "新增对象的id:".$obj['_id']."";;
  18. $count = $collection->count(); //查看集合中的数据量
  19. echo "insert后集合中有[".$count."]条数据";
  20. ?>
  21. 运行结果:
  22. insert前集合中有[2]条数据
  23. ********** mongodb php insert 插入 *************
  24. bool(true)
  25. 新增对象的id:53c908c87f8b9ad7218b4568
  26. Array ( [n] => 0 [connectionId] => 4 [err] => [ok] => 1 )
  27. 新增对象的id:53c908c87f8b9ad7218b4569
  28. insert后集合中有[4]条数据
前面说了到数据库连接操作,请参考:mongodb 用户 权限 设置 详解 对数据库的操作:请参考:mongodb 数据库创建,切换,删除 下面说一下,数据库表的插入操作 1,命令行下的insert操作 > use test; #切换到test数据库 switched to db test > document=({"title" : "linux命令", "auther" : "tank" }); #定义了一个变量 { "title" : "linux命令", "auther" : "tank" } > db.test.insert(document); [...]

人气教程排行