php与mongoDB操作示例详解
mongoDB数据库是一种以json格式存储的数据库,非常适用于各种应用开发,下面我来给各位朋友介绍一些mongoDB学习实例.
mongodb想要整合PHP,需要安装Mongo扩展,这个比较简单,现在说一下MongoDB PHPAPI 及用法.
先看一个简单的例子,实例代码如下:
- <?php
-
- $m = new Mongo();
-
- $db = $m -> comedy;
-
- $collection = $db->collection;
-
- $db->selectCollection("collection");
-
- $obj = array( "title" => "Calvin and Hobbes", "author" => "Bill Watterson" );
-
- $collection->insert($obj);
-
- $obj = array( "title" => "XKCD", "online" => true );
-
- $collection->insert($obj);
-
- $cursor = $collection->find();
-
- foreach ($cursor as $obj) {
-
- echo $obj["title"] . "n";
-
- }
- $m->close();
下面在介绍一些常用的函数,Php代码如下:
- $query = array( "i" => 71 );
-
- $cursor = $collection->find( $query );
-
- while( $cursor->hasNext() ) {
-
- var_dump( $cursor->getNext() );
-
- }
-
- $collection -> findOne();
-
- $collection -> count();
-
- $coll->ensureIndex( array( "i" => 1 ) );
-
- $coll->ensureIndex( array( "i" => -1, "j" => 1 ) );
查询时,每个Object插入时都会自动生成一个独特的_id,它相当于RDBMS中的主键,用于查询时非常方便,Php代码如下:
- <?php
-
- $person = array("name" => "joe");
-
- $people->insert($person);
-
- $joe = $people->findOne(array("_id" => $person['_id']));
-
- ?>
更新时:假如我们想修改下面文档中comments中author的名字,Php代码如下:
- {
-
- "_id" : ObjectId("4b06c282edb87a281e09dad9"),
-
- "content" : "this is a blog post.",
-
- "comments" :
-
- [
-
- {
-
- "author" : "Mike",
-
- "comment" : "I think that blah blah blah...",
-
- },
-
- {
-
- "author" : "John",
-
- "comment" : "I disagree."
-
- }
-
- ]
-
- }
为了改变内部的一个域,我们用 $set,保证文档中其他域不被移除,并且comment的索引也变化,Php代码如下:
- <?php
-
- $collection->update($criteria, array('$set' => array("comments.1" => array("author" => "Jim"))));
-
- ?>
删除一个数据库,Php代码如下:
$m -> dropDB("comedy");
列出所有可用数据库,Php代码如下:
$m->listDBs(); //无返回值
好了就先写这么多了,有兴趣的话可以在网上搜到其他的关于Mongo-php API的用法.
命令行使用实例:
- 1. db.system.users.find()
-
- 2. db.users.count()
-
- 3. db.users.ensureIndex({password:-1})
-
- 4. use test
-
- 5. db.users.getIndexes()
-
- 6. db.repairDatabase()
-
- 7. show users
-
- 8. show dbs
-
- 9. db.users.find({username:{$in:['4d81a82398790']}}).explain()
-
- 10. db.users.dropIndexes()
-
- 11. db.users.find().count()
-
- 12. db.users.find().limit(5)
-
- 13. db.users.find({"username":"ssa"})
-
- 14. show collections
-
- 15. db.users.remove()
-
- 16. db.user.remove({'username':'admin'})
-
- 17. db.user.insert({'username':'admin','age':21,'nickname':'admin'})
-
- 18. db.user.save({'username':'admin','age':21,'info':['12','12313','zzsd']})
-
- 19. db.createCollection("user")
-
- 20. db.dropDatabase()
-
- 21. show collections
-
- 22. db.test.drop()
-
- 23. db.copyDatabase('test','test1')
-
- 24. show profile
-
- 25. db.printCollectionStats()
-
- 26. db.addUser('admin','admin123')
-
- 27. db.setProfilingLevel(2);
-
- 28. db.setProfilingLevel( 1 , 10 );
-
- 29. db.system.profile.find()