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运算,较慢find() method enhancement
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意思是查询到多个,但只删一个。update statement
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 } )Cursor
var cursorName=db.collection.fund(query,...)[.skip(num).limit(num)] //创建游标 cursorName.hasNext() //判断是否有下一个 printjson(cursorName.next()) //输出游标的下一个指向值 cursorName.forEach(function(Obj){process Obj}) //遍历操作游标Index
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
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数据库皆可存取。Data import and export
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'}]};3. Use rs.initiatee (rsconf); to initialize the cluster, mongo will automatically set the smaller ID number as primary, and other mongod processes as secondary. 4. Connect to the secondary process and use the slaveOk() function to initialize the slave process. Operation mongo database in PHP
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

Undress AI Tool
Undress images for free

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

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

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)

Avoid N 1 query problems, reduce the number of database queries by loading associated data in advance; 2. Select only the required fields to avoid loading complete entities to save memory and bandwidth; 3. Use cache strategies reasonably, such as Doctrine's secondary cache or Redis cache high-frequency query results; 4. Optimize the entity life cycle and call clear() regularly to free up memory to prevent memory overflow; 5. Ensure that the database index exists and analyze the generated SQL statements to avoid inefficient queries; 6. Disable automatic change tracking in scenarios where changes are not required, and use arrays or lightweight modes to improve performance. Correct use of ORM requires combining SQL monitoring, caching, batch processing and appropriate optimization to ensure application performance while maintaining development efficiency.

To build a flexible PHP microservice, you need to use RabbitMQ to achieve asynchronous communication, 1. Decouple the service through message queues to avoid cascade failures; 2. Configure persistent queues, persistent messages, release confirmation and manual ACK to ensure reliability; 3. Use exponential backoff retry, TTL and dead letter queue security processing failures; 4. Use tools such as supervisord to protect consumer processes and enable heartbeat mechanisms to ensure service health; and ultimately realize the ability of the system to continuously operate in failures.

ReadonlypropertiesinPHP8.2canonlybeassignedonceintheconstructororatdeclarationandcannotbemodifiedafterward,enforcingimmutabilityatthelanguagelevel.2.Toachievedeepimmutability,wrapmutabletypeslikearraysinArrayObjectorusecustomimmutablecollectionssucha

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

Bref enables PHP developers to build scalable, cost-effective applications without managing servers. 1.Bref brings PHP to AWSLambda by providing an optimized PHP runtime layer, supports PHP8.3 and other versions, and seamlessly integrates with frameworks such as Laravel and Symfony; 2. The deployment steps include: installing Bref using Composer, configuring serverless.yml to define functions and events, such as HTTP endpoints and Artisan commands; 3. Execute serverlessdeploy command to complete the deployment, automatically configure APIGateway and generate access URLs; 4. For Lambda restrictions, Bref provides solutions.

PHP's garbage collection mechanism is based on reference counting, but circular references need to be processed by a periodic circular garbage collector; 1. Reference count releases memory immediately when there is no reference to the variable; 2. Reference reference causes memory to be unable to be automatically released, and it depends on GC to detect and clean it; 3. GC is triggered when the "possible root" zval reaches the threshold or manually calls gc_collect_cycles(); 4. Long-term running PHP applications should monitor gc_status() and call gc_collect_cycles() in time to avoid memory leakage; 5. Best practices include avoiding circular references, using gc_disable() to optimize performance key areas, and dereference objects through the ORM's clear() method.

First, use JavaScript to obtain the user system preferences and locally stored theme settings, and initialize the page theme; 1. The HTML structure contains a button to trigger topic switching; 2. CSS uses: root to define bright theme variables, .dark-mode class defines dark theme variables, and applies these variables through var(); 3. JavaScript detects prefers-color-scheme and reads localStorage to determine the initial theme; 4. Switch the dark-mode class on the html element when clicking the button, and saves the current state to localStorage; 5. All color changes are accompanied by 0.3 seconds transition animation to enhance the user

UseaRESTAPItobridgePHPandMLmodelsbyrunningthemodelinPythonviaFlaskorFastAPIandcallingitfromPHPusingcURLorGuzzle.2.RunPythonscriptsdirectlyfromPHPusingexec()orshell_exec()forsimple,low-trafficusecases,thoughthisapproachhassecurityandperformancelimitat
