Usage of PHP database operation mongodb

墨辰丷
Release: 2023-03-26 15:34:01
Original
1713 people have browsed it

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         //以守护进程方式创建
Copy after login

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()     //显示数据表内全部内容
Copy after login

##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运算,较慢
Copy after login

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意思是查询到多个,但只删一个。
Copy after login

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
}
)
Copy after login

Cursor

var cursorName=db.collection.fund(query,...)[.skip(num).limit(num)] //创建游标
cursorName.hasNext()            //判断是否有下一个
printjson(cursorName.next())          //输出游标的下一个指向值
cursorName.forEach(function(Obj){process Obj})      //遍历操作游标
Copy after login

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()   //重建用了很多出现杂乱的索引
Copy after login

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>
 }
)
Copy after login

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 management

MongoDB 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(&#39;username&#39;,&#39;passwd&#39;);用超级管理员用户登陆后,整个mongo数据库皆可存取。
Copy after login

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:&#39;replname&#39;,members[{_id:0,host:&#39;xxx&#39;},{_id:1,host:&#39;xxy&#39;}]};
Copy after login

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(&#39;host&#39;,port);
$collection=$mongo->dbname->collection;
$cursor=$collection->find();
$cursor->operate();
$mongo->close();
Copy after login

相关推荐:

PHP下 Mongodb 连接远程数据库详解及案例

PECL方式安装php-mongodb扩展步骤详解

PHP+mongoDB数据库操作步骤详解

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!