這篇文章主要介紹了mongodb 命令行下及php中insert數據詳解,需要的朋友可以參考下
前面說了到數據庫連接操作,請參考:mongodb 添加用戶及權限設置詳解
對數據庫的操作:請參考:mongodb 數據庫操作詳解--創建,切換,刪除
下面說一下,數據庫表的插入操作
1,命令行下的insert操作
- > 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數據
- <?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]條數據
新聞熱點
疑難解答