php操作mongoDB实例分析_PHP
本文实例讲述了php操作mongoDB的方法。分享给大家供大家参考。具体分析如下:
mongoDB数据库是一种以json格式存储的数据库,非常适用于各种应用开发,这里就来给各位朋友介绍一些mongoDB学习实例.
mongodb想要整合PHP,需要安装Mongo扩展,这个比较简单,现在说一下MongoDB PHPAPI 及用法.
先看一个简单的例子,实例代码如下:
代码如下:
$m = new Mongo(); //这里采用默认连接本机的27017端口,当然你也可以连接远程主机如 192.168.0.4:27017,如果端口是27017,端口可以省略
$db = $m -> comedy; // 选择comedy数据库,如果以前没该数据库会自动创建,也可以用$m->selectDB("comedy");
$collection = $db->collection; //选择comedy里面的collection集合,相当于RDBMS里面的表,也-可以使用
$db->selectCollection("collection");
$obj = array( "title" => "Calvin and Hobbes", "author" => "Bill Watterson" );
$collection->insert($obj); //将$obj 添加到$collection 集合中
$obj = array( "title" => "XKCD", "online" => true );
$collection->insert($obj);
$cursor = $collection->find();
foreach ($cursor as $obj) { //遍历所有集合中的文档
echo $obj["title"] . "n";
}
$m->close(); //断开MongoDB连接
下面在介绍一些常用的函数,Php代码如下:
代码如下:
$query = array( "i" => 71 );
$cursor = $collection->find( $query );// 在$collectio集合中查找满足$query的文档
while( $cursor->hasNext() ) {
var_dump( $cursor->getNext() );
}
$collection -> findOne();//返回$collection集合中第一个文档
$collection -> count(); //返回$collection集合中文档的数量
$coll->ensureIndex( array( "i" => 1 ) ); // 为i “这一列”加索引 降序排列
$coll->ensureIndex( array( "i" => -1, "j" => 1 ) ); // 为i “这一列”加索引 降序排列 j升序
查询时,每个Object插入时都会自动生成一个独特的_id,它相当于RDBMS中的主键,用于查询时非常方便,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代码如下:
代码如下:
$collection->update($criteria, array('$set' => array("comments.1" => array("author" => "Jim")))); //$criteria 为要更新的元素
?>
删除一个数据库,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()
希望本文所述对大家的php程序设计有所帮助。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.
