mongodb想要整合php,需要安装mongo扩展,这个比较简单,现在说一下mongodb phpapi 及用法
先看一个简单的例子:
php代码
1. comedy; // 选择comedy数据库,如果以前没该数据库会自动创建,也可以用$m->selectdb(comedy);
5.
6. $collection = $db->collection; //选择comedy里面的collection集合,相当于rdbms里面的表,也-可以使用
7. $db->selectcollection(collection);
8.
9. $obj = array( title => calvin and hobbes, author => bill watterson );
10.
11. $collection->insert($obj); //将$obj 添加到$collection 集合中
12.
13.
14. $obj = array( title => xkcd, online => true );
15. $collection->insert($obj);
16. $cursor = $collection->find();
17.
18. foreach ($cursor as $obj) { //遍历所有集合中的文档
19. echo $obj[title] . n;
20. }
21.
22.
23. $m->close(); //断开mongodb连接
下面在介绍一些常用的函数:
php代码
1. $query = array( i => 71 );
2. $cursor = $collection->find( $query ); // 在$collectio集合中查找满足$query的文档
3.
4. while( $cursor->hasnext() ) {
5. var_dump( $cursor->getnext() );
6. }
7.
8. $collection -> findone(); //返回$collection集合中第一个文档
9.
10. $collection -> count(); //返回$collection集合中文档的数量
11. $coll->ensureindex( array( i => 1 ) ); // 为i “这一列”加索引 降序排列
12. $coll->ensureindex( array( i => -1, j => 1 ) ); // 为i “这一列”加索引 降序排列 j升序
查询时,每个object插入时都会自动生成一个独特的_id,它相当于rdbms中的主键,用于查询时非常方便
如:
php代码
1. joe);
4.
5. $people->insert($person);
6.
7. $joe = $people->findone(array(_id => $person['_id']));
8.
9. ?>
更新时:
假如我们想修改下面文档中comments中author的名字
php代码
1. {
2. _id : objectid(4b06c282edb87a281e09dad9),
3. content : this is a blog post.,
4. comments :
5. [
6. {
7. author : mike,
8. comment : i think that blah blah blah...,
9. },
10. {
11. author : john,
12. comment : i disagree.
13. }
14. ]
15. }
为了改变内部的一个域, 我们用 $set (保证文档中其他域不被移除)并且comment的索引也变化
php代码
1. update($criteria, array('$set' => array(comments.1 => array(author => jim)))); //$criteria 为要更新的元素
4.
5. ?>
删除一个数据库
php代码
1. $m -> dropdb(comedy);
列出所有可用数据库
php代码
1. $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()
http://www.bkjia.com/phpjc/632915.htmlwww.bkjia.comtruehttp://www.bkjia.com/phpjc/632915.htmltecharticlemongodb数据库是一种以json格式存储的数据库,非常适用于各种应用开发,下面我来给各位朋友介绍一些mongodb学习实例。 mongodb想要整合php,需...
