The PHP installation USES the mongodb database
- 2020-05-15 02:29:29
- OfStack
Traditional database, we need to operate the database data to write a lot of sql statements, and no rules in data storage, the traditional relational database to build table handling of different field also appears some fatigue, mongo arises at the historic moment, and ajax technology widespread application, json widely accepted format, also makes the mongo closer to the developers.
Introduction and application scenarios of mongo
MongoDB is a document-oriented, non-relational database (NoSQL) that is stored in json format. Mongo DB is a good implementation of the object-oriented idea (OO idea). In Mongo DB, every record is an Document object. The biggest advantage of Mongo DB is that all data persistence operations do not require developers to manually write SQL statements, and it is easy to implement CRUD operations by calling methods directly.
mongo can be used in the following scenarios:
Store large, low-value data
json and object type data
Web caching data
Comments and subcomment classes have significant affiliation data
Multi-server data, with its built-in MapReduce for easy global traversal.
Install and use mongodb
In our website https: / / www mongodb. org on/to the latest stable version can be downloaded, mongo is the official has been compiled, after decompression can use the commands in bin directory.
Configure the mongo.conf file before using it
port=xxxxx // Represents the port number, which defaults to 27017
dbpath=/usr/local/mongodb/db // Database path
logpath=/usr/local/mongodb/logs/mongodb.log // Log path
logappend=true // Log files are automatically accumulated, not overwritten
fork=ture // Created as a daemon
Database and data table can be created directly, that is, without switching, can be used directly, can be created when used, mongo can also directly write js script, can be directly run, mongo if you do not specify _id field, mongo will automatically add 1.
mongo's various commands
The essence of mongo's commands is that the 10-point complex set of commands in one block makes mongo's queries gorgeous and efficient. Each table in mongo is called an collection(collection), and using a command similar to MySQL, switch to the database directly for each collection operation. The command consists of the method (func()), the query body (written in {}), and the operator (starting with $).
Basic commands
show dbs // View database
use dbname // Switch to database
db.createCollection('collection') // Create a data table
db.collection.drop() // Delete data table
db.dropDatabase() // Delete the database
db.collection.insert({data}) // Insert data
db.collection.find() // Displays all contents of the data table
The query body
{key.attr.attr:value} // Ordinary type
{key:{$ne|$gt|$gte|$lt|$lte|$in|$nin|$all:value}} //key meet $oper value The value of the
{$or|$and|$not|$nor:[{key1:{$gt:value}},{key2:{$ne:value}}]} // with $oper At the same time limit key1,key2 The conditions of the
{key:{$mod{8,2}}} // Take out the key right 8 Take over for 2 The value of the.
{key:{$exist:1}} // Take out the key The value in which the column exists.
{key:{$type:String|Double|Array|Date|Object|Boolean|......}}// The query key A type of type The columns of the
{key:{$regex:/pattern/}} // Through the regular query, the efficiency is low
{$where:'this.attr.express.....'} // Use directly where Statements, 2 Into the system to JS Operations, slower
The find() method is enhanced
db.collection.find(query,{ The column to pull out :1, Unwanted columns :0})
db.collection.find(query).skip( Number of lines skipped ).limit( Limit the number of messages );
db.collection.find(query).explain() // with MYSQL Interpretation statement 1 The sample.
db.collection.remove(query,[justone]) // If you don't specify query, Delete all; [justone] The default is false Multiple queries are found, but only deleted 1 A.
update statement
db.collection.update(query,{key:newvalue}) // Note: the new value overrides the old value , That is, the data is left only as defined in the statement key
db.collection.update(query,
{
$set:{key:newvalue},
$unset:{key:value},
$rename:{key:value},
$inc:{key:value},
......
},
{
multi:true, // Change all eligible to default to false
upsert:true // No, just added, by default false
}
)
The cursor
var cursorName=db.collection.fund(query,...)[.skip(num).limit(num)] // Create a cursor
cursorName.hasNext() // Judge if there are any 1 a
printjson(cursorName.next()) // Output below the cursor 1 Point to the values
cursorName.forEach(function(Obj){process Obj}) // Traverse the operation cursor
The index
db.collection.getIndexes() // View index
db.collection.ensureIndex({key:1/-1[,key.attr:1/-1]},{unique:1( If only 1)},{sparse:1( Is not empty )})// Add the positive sequence / Reverse index
db.collection.dropIndex({key:1/2}) // Remove the index
db.collection.reIndex() // Reconstruction USES a lot of index clutter
MapReduce
MapReduce is a very powerful traversal tool built into mongo. To use MapReduce, you need to implement its map and reduce functions
db.runCommand(
{
mapReduce: collection, // The data table to operate on
map: function(){emit(key1,key2)}, // right key1 and key2 Data mapping
reduce: function(key,value){}, // right key Values and data sets value operate
out: <output>,
query: <document>,
sort: <document>,
limit: <number>,
finalize: <function>,
scope: <document>,
jsMode: <boolean>,
verbose: <boolean>
}
)
More detailed commands in Chinese community http mongo: / / docs mongoing. com/manual zh/find.
Users, data import and export, and clustering for mongo
User management
MongoDB does not enable authorization by default. You can add the --auth or --keyFile option to enable authorization when the server is started. To use the configuration file, use the security.authorization or security.keyFile Settings.
MongoDB provides native roles, each of which provides a specific 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/reclaiming different roles to users.
To add a role, first add an administrator role to the admin database, and then use the administrator role to add a different role to each library.
use admin;( Switch to the admin Database, operation on this library )
db.createUser(
{
user: "username",
pwd: "password",
roles:
[
{
role: "userAdminAnyDatabase",
db: "admin"
}
]
}
)
use database;
db.auth('username','passwd'); After logging in with the super admin user, the whole mongo All databases are accessible.
Data import and export
We use the tools provided by mongo to import and export. It is better to export csv format under the directory mongo/bin to facilitate data exchange.
./mongoexport -d dataname -c tablename -f key1,key2 -q 'query' -o ainname --csv// Export data, default is json format
./mongoimport -d dataname -c tablename --type json --file ./path // Import data, default is json format
mongo database cluster
Add option when opening mongod --replSet replname;
Connect an mongod process on the mongo client, enter the admin database, and 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 set the smaller id to primary and the other mongod processes to secondary.
Connect to the secondary process and use the slaveOk() function to initialize the slave process.
The mongo database is manipulated in PHP
Let's start by adding the mongo extension to php (see PHP under linux for the method). We can then use the mongo class library in our script.
Unlike other class libraries, which only have one core class, mongo has four classes, which are:
The Mongo class, the base class, has the methods to connect, close the connection, and operate on the global database.
The mongoDB class is obtained through the selectDB() method and has table-level methods.
MongoCollection class, 1 like Mongo-
>
dbname-
>
collection, or simply instantiated with the MongoDB class and database name, has basic operations on the data.
The MongoCursor class, obtained by MongoCollection via the find() method, has normal cursor traversal operations.
Here is a typical mongo operation:
show dbs // View database
use dbname // Switch to database
db.createCollection('collection') // Create a data table
db.collection.drop() // Delete data table
db.dropDatabase() // Delete the database
db.collection.insert({data}) // Insert data
db.collection.find() // Displays all contents of the data table
0