In traditional databases, we have to write a large number of SQL statements to operate database data. Moreover, when storing irregular data, the processing of different fields when creating tables in traditional relational databases is also a bit weak. Mongo came into being. Moreover, the widespread 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:
Storage large-size, low-value data
json and object type data
Website cache data
Comments and sub-comments have obvious affiliation data
Multiple server data, its built-in MapReduce is very Easy to implement global traversal.
Install and use mongodb
We can download its latest stable version on the official website https://www.mongodb.org/. Mongo is officially compiled. You can use its commands after decompression. All the commands are in bin Under contents.
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 databases and data tables can be created directly, that is, they can be used directly without switching. They are created when used. You can also directly write js scripts in mongo and run them directly. If in mongo If you do not specify the _id field, mongo will automatically add one.
Various commands of mongo
Mongo’s commands are its essence. These very complex commands are gathered together to make mongo’s query brilliant 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/.
Mongo user, data import, export and cluster
User management
MongoDB does not enable authorization by default. 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 library.
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 mongo’s own tools to import and export. In the mongo/bin directory, 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//导出数据,默认为json格式 ./mongoimport -d dataname -c tablename --type json --file ./path //导入数据,默认为json格式
mongo database cluster
Add the option --replSet replname when opening mongod;
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'}]};
Use rs.initiatee(rsconf); to initialize the cluster, mongo will automatically change the id The one with the smallest number is set as primary, and the other mongod processes are set as secondary.
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 PHP under Linux for the method). Then, we can use the mongo class function library in the script.
Unlike other class libraries that have only one core class, mongo has four classes, namely:
Mongo class, the basic class, has methods for connecting, closing connections, and operating on the global database.
MongoDB class, the Mongo class is obtained through the selectDB() method and has table-level operation methods.
The MongoCollection class is generally instantiated by Mongo->dbname->collection or directly using the MongoDB class and database name. It has basic operations on data.
MongoCursor class, obtained from MongoCollection through the find() method, has ordinary cursor traversal operations.
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();
For more articles related to installing and using mongodb database in cdnoss PHP, please pay attention to the PHP Chinese website!