Usage of PHP database operation mongodb
This article mainly introduces the usage of PHP database operation mongodb. It analyzes the functions, installation, basic commands, usage and related precautions of MongoDB in detail in the form of examples. Friends in need can refer to it
The details are as follows:
In traditional databases, we have to write a large number of SQL statements to operate database data, and when storing irregular data, the processing of different fields when creating tables in traditional relational databases is also difficult. It seems a bit weak, mongo came into being, and the wide application of ajax technology and the wide acceptance of json format also make mongo closer to developers.
Introduction to mongo and application scenarios
MongoDB is a document-oriented non-relational database (NoSQL) that is stored in json format. Mongo DB implements object-oriented thinking (OO thinking) very well. In Mongo DB, every record is a Document object. The biggest advantage of Mongo DB is that all data persistence operations do not require developers to manually write SQL statements, and CRUD operations can be easily implemented by directly calling methods.
mongo can be used in the following scenarios:
Storing large-size, low-value data
json and object type data
Website cache data
Comment and sub-comment categories have obvious affiliation data
Multi-server data, its built-in MapReduce can easily realize global traversal.
Installing and using mongodb
We can download the latest version from the official website https://www.mongodb.org/ Stable version, mongo has been officially compiled and can be used after decompression. Its commands are all in the bin directory.
Configure the mongo.conf file first before use
port=xxxxx //代表端口号,如果不指定则默认为 27017 dbpath=/usr/local/mongodb/db //数据库路径 logpath=/usr/local/mongodb/logs/mongodb.log //日志路径 logappend=true //日志文件自动累加,而不是覆盖 fork=ture //以守护进程方式创建
Both the database and the data table can be created directly, that is, there is no need to switch, use it directly, use It is created immediately. You can also write js scripts directly in mongo and run it directly. If the _id field is not specified in mongo, mongo will automatically add one.
Various commands of mongo
The commands of mongo are its essence. These very complex commands are gathered together, making mongo’s query become more complex. Be gorgeous and efficient. Each table in mongo is called a collection. The use of commands is similar to MySQL. Switch to the database to directly operate each collection. Its command consists of method (func()), query body (written in {}) and operator (starting with $).
Basic commands
show dbs //查看数据库 use dbname //切换到数据库 db.createCollection('collection') //创建数据表 db.collection.drop() //删除数据表 db.dropDatabase() //删数据库 db.collection.insert({data}) //插入数据 db.collection.find() //显示数据表内全部内容
##Query body
##{key.attr.attr:value} //普通式 {key:{$ne|$gt|$gte|$lt|$lte|$in|$nin|$all:value}} //key满足 $oper value的值 {$or|$and|$not|$nor:[{key1:{$gt:value}},{key2:{$ne:value}}]} //用$oper同时限定key1,key2的条件 {key:{$mod{8,2}}} //取出key对8取余为2的值。 {key:{$exist:1}} //取出key列存在的值。 {key:{$type:String|Double|Array|Date|Object|Boolean|......}}//查询key类型为type的列 {key:{$regex:/pattern/}} //通过正则查询,效率较低 {$where:'this.attr.express.....'} //直接用where语句,二进制转为JS运算,较慢
db.collection.find(query,{要取出的列:1,不需要的列:0}) db.collection.find(query).skip(跳过的行数).limit(限制信息条数); db.collection.find(query).explain() //与MYSQL的解释语句一样。 db.collection.remove(query,[justone]) //如不指定query,全部删除;[justone]默认为false意思是查询到多个,但只删一个。
db.collection.update(query,{key:newvalue}) //注意:新值会覆盖旧值,即数据只剩下语句中定义的key db.collection.update(query, { $set:{key:newvalue}, $unset:{key:value}, $rename:{key:value}, $inc:{key:value}, ...... }, { multi:true, //改变所有符合条件的,默认为false upsert:true //没有的话刚添加,默认为false } )
var cursorName=db.collection.fund(query,...)[.skip(num).limit(num)] //创建游标 cursorName.hasNext() //判断是否有下一个 printjson(cursorName.next()) //输出游标的下一个指向值 cursorName.forEach(function(Obj){process Obj}) //遍历操作游标
db.collection.getIndexes() //查看索引 db.collection.ensureIndex({key:1/-1[,key.attr:1/-1]},{unique:1(是否唯一)},{sparse:1(是否非空)})// 添加正序/倒序索引 db.collection.dropIndex({key:1/2}) //删除索引 db.collection.reIndex() //重建用了很多出现杂乱的索引
MapReduce is a very powerful traversal operation tool built into mongo. To use it, you need to implement Its map and reduce functions
db.runCommand( { mapReduce: collection, //要操作的数据表 map: function(){emit(key1,key2)}, //对key1和key2进行数据映射 reduce: function(key,value){}, //对key值和数据组value进行操作 out: <output>, query: <document>, sort: <document>, limit: <number>, finalize: <function>, scope: <document>, jsMode: <boolean>, verbose: <boolean> } )
More and more detailed commands can be found in the mongo Chinese community http://docs.mongoing.com/manual -zh/ found.
Mongo’s users, data import and export and cluster
User managementMongoDB is not enabled by default Turn on authorization. You can add the --auth or --keyFile option when starting the server to enable authorization. If using a configuration file, use security.authorization or security.keyFile settings.
MongoDB provides its own roles, each of which provides a clear role for a common use case. For example, roles such as read, readWrite, dbAdmin, and root. We manage users by creating users, creating roles, and assigning/recycling different roles to users.
When adding a role, you must first add an administrator role in the admin database, and then use the administrator role to add different roles in each database.
use admin;(切换到admin数据库,对此库操作) db.createUser( { user: "username", pwd: "password", roles: [ { role: "userAdminAnyDatabase", db: "admin" } ] } ) use database; db.auth('username','passwd');用超级管理员用户登陆后,整个mongo数据库皆可存取。
We use the tools that come with mongo to import and export, in the mongo/bin directory Next, it is best to export in csv format to facilitate data exchange.
./mongoexport -d dataname -c tablename -f key1,key2 -q 'query' -o ainname --csv//Export data, the default is json format
./mongoimport -d dataname - c tablename --type json --file ./path //Import data, the default is json format
mongo database cluster
1. Add the option --replSet replname;## when opening mongod
#2. Connect to a mongod process on the mongo client, enter the admin database, and then declare the mongoconf variable:use admin; var rsconf={_id:'replname',members[{_id:0,host:'xxx'},{_id:1,host:'xxy'}]};
We first add the mongo extension to php (see the method: http://www.jb51.net /article/96829.htm). Then, we can use the mongo class function library in the script.
不同于其他的类库只有一个核心类,mongo有四个类,分别是:
Mongo类,基础类,拥有连接、关闭连接、对全局数据库的操作方法。
mongoDB类,邮Mongo类通过selectDB()方法得到,拥有表级的操作方法。
MongoCollection类,一般由Mongo->dbname->collection或直接用MongoDB类和数据库名实例化得到,拥有对数据的基本操作。
MongoCursor类,由MongoCollection通过find()方法得到,拥有普通的游标遍历操作。
以下是一个典型的mongo操作:
$mongo=new Mongo(); $mongo->connect('host',port); $collection=$mongo->dbname->collection; $cursor=$collection->find(); $cursor->operate(); $mongo->close();
相关推荐:
The above is the detailed content of Usage of PHP database operation mongodb. For more information, please follow other related articles on the PHP Chinese website!

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 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.

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 used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

When developing an e-commerce website, I encountered a difficult problem: how to provide users with personalized product recommendations. Initially, I tried some simple recommendation algorithms, but the results were not ideal, and user satisfaction was also affected. In order to improve the accuracy and efficiency of the recommendation system, I decided to adopt a more professional solution. Finally, I installed andres-montanez/recommendations-bundle through Composer, which not only solved my problem, but also greatly improved the performance of the recommendation system. You can learn composer through the following address:

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip
