Traditional database, we want to manipulate database data to write a large number of SQL statements, and in the storage of irregular data, the traditional relational database table when the processing of the different fields also appear somewhat weak, Mongo came into being, and the wide application of AJAX technology, JSON format widely accepted, It also makes MONGO closer to developers.
MONGO Introduction and Application Scenario
MongoDB is a document-oriented, non-relational database (NoSQL) that is stored in JSON format. Mongo DB is a good implementation of object-oriented thinking (Oo idea), in Mongo db each record is a document object. The biggest advantage of Mongo DB is that all data persistence requires no developers to write SQL statements manually, and it is easy to invoke methods to implement CRUD operations.
MONGO can be used in the following scenarios:
- Store large, low-value data
- JSON and Object type data
- Site cache Data
- Comments, sub-comment classes have explicit dependency data
- Multi-server data, its built-in MapReduce is easy to realistically traverse globally.
Installing and Using MongoDB
We can download to its latest stable version on the official website https://www.mongodb.org/, MONGO is the official already compiles, the decompression can use its command in the bin directory.
First configure the mongo.conf file before use
port=xxxxx //代表端口号,如果不指定则默认为 27017 dbpath=/usr/local/mongodb/db //数据库路径logpath=/usr/local/mongodb/logs/mongodb.log //日志路径logappend=true //日志文件自动累加,而不是覆盖fork=ture //以守护进程方式创建
Database and data tables can be directly created, that is, without switching, direct use, when used to create, MONGO can also directly write JS script, can run directly, MONGO if you do not specify _id field, MONGO will automatically add one.
Various commands of the MONGO
MONGO's commands are the essence, and these very complex commands are set together, making MONGO's queries more brilliant and efficient. Each table in the MONGO is called a Collection (collection), using commands similar to MySQL, to switch to the database directly for each collection operation. Its command consists of the method (func ()), the body of the query ( written in {} ), and the 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 enhancements
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}) //注意:新值会覆盖旧值,即数据只剩下语句中定义的keydb.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 that uses it to implement its map and reduce two 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 detailed commands can be found in MONGO's Chinese community http://docs.mongoing.com/manual-zh/.
MONGO users, data import and export, and cluster user management
MongoDB does not turn on authorization by default. You can turn on authorization by adding the--auth or--keyfile option when the server is turned on. Use the Security.authorization or security.keyfile settings if you are using a configuration file.
MONGODB provides its own role, and each role provides a clear role for a common use case. Roles such as read, ReadWrite, dbAdmin, and Root. We manage users by creating users, creating roles, assigning/reclaiming different roles for users.
When you add a role, you add an administrator role in the Admin database and then use the Administrator role to add different roles to each library.
use admin;(切换到admin数据库,对此库操作)db.createUser( { user: "username", pwd: "password", roles: [ { role: "userAdminAnyDatabase", db: "admin" } ] })use database;db.auth(‘username‘,‘passwd‘);用超级管理员用户登陆后,整个mongo数据库皆可存取。
Data Import Export
We use MONGO's own tools for import and export, in the Mongo/bin directory, it is best to export CSV format, easy to exchange data.
./mongoexport -d dataname -c tablename -f key1,key2 -q ‘query‘ -o ainname --csv//导出数据,默认为json格式./mongoimport -d dataname -c tablename --type json --file ./path //导入数据,默认为json格式
MONGO DB cluster
- Add options when opening Mongod--replset replname;
On the MONGO client, connect to the previous Mongod process, go to the admin database, and then declare the mongoconf variable:
use admin;var rsconf={_id:‘replname‘,members[{_id:0,host:‘xxx‘},{_id:1,host:‘xxy‘}]};
With Rs.initiatee (rsconf), to initialize the cluster, MONGO will automatically set the ID number to primary, and the other Mongod process to secondary.
- Connect the secondary process, using the Slaveok () function, to initialize the process from.
Working with MONGO database in PHP
Let's add the MONGO extension to PHP first (see PHP under Linux). Then we can use the MONGO class library in the script.
Unlike other class libraries, there is only one core class, and MONGO has four classes, namely:
- The MONGO class, the base class, has a connection, closes the connection, and operates on the global database.
- MongoDB class, Mail MONGO class is obtained through the Selectdb () method, which has a table-level operation method.
- The Mongocollection class, typically instantiated by mongo->dbname->collection or directly with MongoDB classes and database names, has basic operations on the data.
- The Mongocursor class, obtained by mongocollection through the Find () method, has a normal cursor traversal operation.
The following is a typical MONGO operation:
$mongo=new Mongo();$mongo->connect(‘host‘,port);$collection=$mongo->dbname->collection;$cursor=$collection->find();$cursor->operate();$mongo->close();
If you think this blog is helpful to you, you can recommend or follow me, if you have any questions, you can leave a comment under the discussion, thank you.
Database in PHP four, MongoDB