mongodb 命令行下及php中insert數(shù)據(jù)詳解
前面說了到數(shù)據(jù)庫連接操作,請參考:mongodb 添加用戶及權限設置詳解
對數(shù)據(jù)庫的操作:請參考:mongodb 數(shù)據(jù)庫操作詳解--創(chuàng)建,切換,刪除
下面說一下,數(shù)據(jù)庫表的插入操作
1,命令行下的insert操作
> use test; #切換到test數(shù)據(jù)庫 switched to db test > document=({"title" : "linux命令", "auther" : "tank" }); #定義了一個變量 { "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擴展insert數(shù)據(jù)
<?php //$mongo = new Mongo("mongodb://192.168.10.202:27017"); //鏈接遠程數(shù)據(jù)庫 $mongo = new Mongo(); //鏈接遠程數(shù)據(jù)庫 $curDB = $mongo->selectDB("test"); //選擇要操作的數(shù)據(jù)庫,如果不存在,則自動創(chuàng)建 $collection = $curDB->selectCollection("test"); //選中一個集合(理解為 table),如果不存在,則自動創(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); //打印插入后的結果是bool型的 echo "<Br>新增對象的id:".$obj['_id']."<Br>"; $obj = array("title"=>"朝發(fā)白帝城","auther"=>"李白"); $rel = $collection->insert($obj,array('safe'=>true)); //safe 表示是否返回操作結果信息,返回的信息為 array print_r($rel); //插入后的結果是數(shù)組 echo "<Br>新增對象的id:".$obj['_id']."<Br>";; $count = $collection->count(); //查看集合中的數(shù)據(jù)量 echo "insert后集合中有[".$count."]條數(shù)據(jù)<Br>"; ?>
運行結果:
insert前集合中有[2]條數(shù)據(jù)
********** mongodb php insert 插入 *************
bool(true)
新增對象的id:53c908c87f8b9ad7218b4568
Array ( [n] => 0 [connectionId] => 4 [err] => [ok] => 1 )
新增對象的id:53c908c87f8b9ad7218b4569
insert后集合中有[4]條數(shù)據(jù)
相關文章
MongoDB數(shù)據(jù)去重與保存最新數(shù)據(jù)操作指南
在 MongoDB 數(shù)據(jù)庫中,我們經(jīng)常需要進行數(shù)據(jù)去重并保留最新的數(shù)據(jù),本文將介紹如何使用 MongoDB 聚合操作完成這一任務,并將結果保存到新的集合或者覆蓋原有的集合,感興趣的小伙伴跟著小編一起來看看吧2024-01-01MongoDB錯誤32-bit servers don''t have journaling enabled by de
這篇文章主要介紹了MongoDB錯誤32-bit servers don't have journaling enabled by default解決方法,需要的朋友可以參考下2014-10-10解決MAC上啟動mongod報錯exiting with code 1的問題
這篇文章主要介紹了解決MAC上啟動mongod報錯exiting with code 1的問題,本文給大家介紹的非常詳細對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-12-12