這篇文章主要介紹了mongodb 命令行下及php中insert數(shù)據(jù)詳解,需要的朋友可以參考下
前面說了到數(shù)據(jù)庫(kù)連接操作,請(qǐng)參考:mongodb 添加用戶及權(quán)限設(shè)置詳解
對(duì)數(shù)據(jù)庫(kù)的操作:請(qǐng)參考:mongodb 數(shù)據(jù)庫(kù)操作詳解--創(chuàng)建,切換,刪除
下面說一下,數(shù)據(jù)庫(kù)表的插入操作
1,命令行下的insert操作
- > use test; #切換到test數(shù)據(jù)庫(kù)
- switched to db test
- > document=({"title" : "linux命令", "auther" : "tank" }); #定義了一個(gè)變量
- { "title" : "linux命令", "auther" : "tank" }
- > db.test.insert(document); #插入變量
- > db.test.find(); #查看插入的數(shù)據(jù)
- { "_id" : ObjectId("53c8fc1cf062ac30ee8b9d2d"), "title" : "linux命令", "auther" : "tank" }
- > db.test.insert({"title" : "51yip", "auther" : "tank" }); #直接插入數(shù)據(jù)
- > db.test.find(); #查看
- { "_id" : ObjectId("53c8fc1cf062ac30ee8b9d2d"), "title" : "linux命令", "auther" : "tank" }
- { "_id" : ObjectId("53c8f6fff062ac30ee8b9d2e"), "title" : "51yip", "auther" : "tank" }
2,利用php擴(kuò)展insert數(shù)據(jù)
- <?php
- //$mongo = new Mongo("mongodb://192.168.10.202:27017"); //鏈接遠(yuǎn)程數(shù)據(jù)庫(kù)
- $mongo = new Mongo(); //鏈接遠(yuǎn)程數(shù)據(jù)庫(kù)
- $curDB = $mongo->selectDB("test"); //選擇要操作的數(shù)據(jù)庫(kù),如果不存在,則自動(dòng)創(chuàng)建
- $collection = $curDB->selectCollection("test"); //選中一個(gè)集合(理解為 table),如果不存在,則自動(dòng)創(chuàng)建
- //$collection->drop(); //清空集合 testCollection
- $count = $collection->count(); //查看集合中的數(shù)據(jù)量
- echo "insert前集合中有[".$count."]條數(shù)據(jù)<Br>"; //這里的二條數(shù)據(jù)主命令行下插入的。
- echo "<br>********** mongodb php insert 插入 *************<br>";
- $obj = array("title"=>"圍城","auther"=>"錢鐘書");
- $rel = $collection->insert($obj);
- var_dump($rel); //打印插入后的結(jié)果是bool型的
- echo "<Br>新增對(duì)象的id:".$obj['_id']."<Br>";
- $obj = array("title"=>"朝發(fā)白帝城","auther"=>"李白");
- $rel = $collection->insert($obj,array('safe'=>true)); //safe 表示是否返回操作結(jié)果信息,返回的信息為 array
- print_r($rel); //插入后的結(jié)果是數(shù)組
- echo "<Br>新增對(duì)象的id:".$obj['_id']."<Br>";;
- $count = $collection->count(); //查看集合中的數(shù)據(jù)量
- echo "insert后集合中有[".$count."]條數(shù)據(jù)<Br>";
- ?>
運(yùn)行結(jié)果:
insert前集合中有[2]條數(shù)據(jù)
********** mongodb php insert 插入 *************
bool(true)
新增對(duì)象的id:53c908c87f8b9ad7218b4568
Array ( [n] => 0 [connectionId] => 4 [err] => [ok] => 1 )
新增對(duì)象的id:53c908c87f8b9ad7218b4569
insert后集合中有[4]條數(shù)據(jù)
新聞熱點(diǎn)
疑難解答
圖片精選