Xiaobai must understand the MongoDB summary

I. Understanding of MongoDB

1. What is MongoDB?

MongoDB is an open source product between relational database and non-relational database. It is NoSQL database closest to relational database. It expands on lightweight JSON interchange, called BSON, to describe its unstructured data types. However, it can also store more complex data types. It is similar to Redis in the last article. Although both are NoSQL, MongoDB is more like a traditional database than Redis. In the early years, we first had Relation Database, and then a lot of very complex queries emerged, which used a lot of nesting and a lot of join operations. So when we designed the database, we also thought about how to apply their relationships so that writing Queries would make the database as efficient as possible. It turns out that not every system needs such a complex relational database. Some simple sites, such as blogs and social networking sites, can sever all relationships between databases. The benefit of this is that it becomes easier to design the database and write the Query. Then, the query might take less time. Because query is simpler, there are fewer resource-consuming join operations, and the speed increases naturally. As said, Query is simple and has a lot of things that MySQL used to find, but now the relationship is gone and can’t be found through Mongo. We can only capture several sets of data locally and then join locally, so it may consume a lot of resources at this point. Here we can see. How you choose a database depends entirely on the Data Model you need to work with. If they have a lot of relationships, a lot of relationships, then MySQL is the first choice. If the relationship is not that close, then NoSQL will be a great tool.

Like Redis, MongoDB is a key-value storage system. It has the following characteristics:

  • Collective-oriented storage, easy to store object type data.
  • Pattern freedom.
  • Supports dynamic query.
  • Full index support, including internal objects.
  • Supports query.
  • Supports replication and failover.
  • Use efficient binary data storage, including large objects (such as videos).
  • Automatically handles fragmentation to support cloud level extensibility
  • supportPythonPHPRubyJavaCC#JavascriptPerlC++Language drivers are also available in the community onErlang.NETAnd other platform drivers.
  • The file storage format isBSON(aJSON“).
  • Accessible via the network.

2, MongoDB and MySQL performance comparison

Like MySQL, MongoDB offers a wealth of functionality and capabilities that go far beyond those provided in a simple key-value store. MongoDB has query language, powerful auxiliary indexes (including text search and geographic space), powerful aggregation framework for data analysis and so on. With MongoDB, you can also use these capabilities, as shown in the following table, across more diverse data types and data sizes than with relational databases.

MySQL MongoDB
Rich data model no is
dynamicSchema no is
The data type is is
Data localization no is
Field update is is
Ease of programming no is
Complex transaction is no
The audit is is
Automatic subdivision no is

Many of the concepts in MySQL have similar analogies to MongoDB. This table Outlines some common concepts in each system.

MySQL MongoDB
table A collection of
line The document
column field
joins Embed documents or links

3. Application scope and limitation

MongoDB’s primary goal is to bridge the gap between key-value storage, which provides high performance and high scalability, and traditional RDBMS systems, which are rich in functionality. The application scope of MongoDB is as follows:

  • Website data: MongoIdeal for real-time inserts, updates, and queries, with the replication and high scalability required for real-time site data storage.
  • Cache:Because of its high performance,MongoIt is also suitable as a caching layer for information infrastructure. After the system restarts, theMongoThe persistent cache layer is built to avoid overloading the underlying data source.
  • Large, low-value data: It can be expensive to store some data in a traditional relational database. Before that, programmers often used traditional files for storage.
  • Highly scalable scenarios: MongoGreat for databases with dozens or hundreds of servers.MongoThe roadmap for theMapReduceBuilt-in engine support.
  • For object and JSON data storage: MongoBSONThe data format is ideal for storage and query in a documented format.

MongoDB also has restrictions on the following scenarios:

  • Highly transactional systems: such as banking or accounting systems. Traditional relational databases are still better suited for applications that require a large number of atomically complex transactions.
  • Traditional business intelligence applications: problem specificBIThe database produces highly optimized queries. For such applications, a data warehouse may be a more appropriate choice.
  • Need to beSQLThe problem.

Second, MongoDB installation

Environment to prepare

  • CentOS7
  • Directing a 3.6

Installation steps

1. Create oneMongo - org - 3.6. Repofile
Vi/etc/yum. Repos. D/mongo - org - 3.6. RepoCopy the code

Add the following to the file:

[mongo - org - 3.6] name = mongo Repository baseurl=https://repo.mongodb.org/yum/amazon/2013.03/mongodb-org/3.6/x86_64/ gpgkey=https://www.mongodb.org/static/pgp/server-3.6.asc gpgcheck = 1 enabled = 1Copy the code

Exit the editing mode and enter the following command to install:

sudo yum install -y mongodb-org
Copy the code

To install a specific version of MongoDB, specify each component package separately and append the version number to the package name, as follows:

Sudo yum install -y mongodb-org-3.6.3 mongodb-org-server-3.6.3 mongodb-org-shell-3.6.3 mongodb-org-mongos-3.6.3 Mongo - org - tools - 3.6.3Copy the code

You can specify any available MongoDB version. However, Yum updates packages when new versions become available. To prevent accidental upgrades, nail the package. To fix the package, add the following exclude directive to the /etc/ym.conf file:

exclude=mongodb-org,mongodb-org-server,mongodb-org-shell,mongodb-org-mongos,mongodb-org-tools
Copy the code

Let’s just run the following command:

mongod -repair
Copy the code

If you see the following, the installation is successful!

Create a db and check where mongo is installed:

mkdir db
whereis mongod
Copy the code

Start mongodb after installation and check mongob startup status:

systemctl start mongod.service
systemctl status mongod.service
Copy the code

If the following information is displayed, the startup is successful.

After successfully starting MongoDB, create a command line and enter mongo to log in. Then you can perform some database operations.

mongo
Copy the code

Explain MongoDB data types and common commands

The data types of MongoDB are as follows:

The data type describe
String A string. Data types commonly used to store data. inMongoDB,UTF-8Encoded strings are legal.
Integer Integer value. Used to store values. According to the server you use, can be divided into32or64position
Boolean Boolean value. Used to store Boolean values (true/false).
Double A double precision floating point value. Used to store floating point values.
Min/Max keys A value andBSON(binaryJSON) the lowest and highest values of the element.
Arrays Use to store an array or list or multiple values as a key.
Timestamp The time stamp. Record the time when the document was modified or added.
Object For inline documents.
Null Used to create null values.
Symbol Symbols. This data type is basically the same as a string type, except that it is generally used in languages that use special symbolic types.
Date Date time. withUNIXTime format to store the current date or time. You can specify your own date and time: createDateObject, passing in the year, month and day information.
Object ID objectID. Used to create documentsID.
Binary Data Binary data. Used to store binary data.
Code Code type. Used for storage in documentsJavaScriptThe code.
Regular expression Regular expression type. Used to store regular expressions.

Here are some common MongoDB commands!

1. Create a database

Use Database name: Creates a new database. Note: If the database does not exist, then create, if the database exists, then switch. If the database is created, no action is taken, then the database is automatically deleted

Example:

> use stu
switched to db stu
Copy the code
2. Check the database

Show DBS: Shows how many databases exist

Example:

> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
Copy the code
3. Create a collection

Db. Collection name. Insert ({}) : Add documents to the collection. Inside {} is the JSON document. Note: the collection in mongodb is created implicitly, that is, it is used directly without being created. Db displays the current database.

Example:

> db.php.insert({"name":"xiaoming","age":20,"email":"[email protected]"})
WriteResult({ "nInserted" : 1 })
> db.php.insert({"name":"xiaohong","age":18,"email":"[email protected]"})
WriteResult({ "nInserted" : 1 })
Copy the code
4. View collections

Show tables: View collections in the current database

Example:

> show tables
php
Copy the code
5, query the documents in the collection

Db.collection name. find() : Queries all documents under this collection in the current database

Example:

> db.php.find()
{ "_id" : ObjectId("5b9318ac487b851e62879578"), "name" : "xiaoming", "age" : 20, "email" : "[email protected]" }
{ "_id" : ObjectId("5b9319a2487b851e62879579"), "name" : "xiaohong", "age" : 18, "email" : "[email protected]" }
Copy the code

Db. collection name. find: Queries the first document under this collection in the current database

Example:

> db.php.find function (query, fields, limit, skip, batchSize, options) { var cursor = new DBQuery(this._mongo, this._db, this, this._fullName, this._massageObject(query), fields, limit, skip, batchSize, options || this.getQueryOptions()); { const session = this.getDB().getSession(); const readPreference = session._serverSession.client.getReadPreference(session); if (readPreference ! == null) { cursor.readPref(readPreference.mode, readPreference.tags); } const readConcern = session._serverSession.client.getReadConcern(session); if (readConcern ! == null) { cursor.readConcern(readConcern.level); } } return cursor; }Copy the code
6. Delete the collection

Db. collection name. drop() : deletes a collection from the current database

Example:

> db.php.drop()
true
Copy the code
Delete the database

Db.dropdatabase () : Deletes the current database

> db.dropDatabase()
{ "dropped" : "stu", "ok" : 1 }
Copy the code
8. Help commands

Help: global help command

> help db.help() help on db methods db.mycoll.help() help on collection methods sh.help() sharding helpers rs.help() replica set helpers help admin administrative help help connect connecting to a db help help keys key shortcuts help misc misc things to know help mr mapreduce show dbs show database names show collections show collections in current database show users show users in current database show profile show most recent system.profile entries with time >= 1ms  show logs show the accessible logger names show log [name] prints out the last segment of log in memory, 'global' is default use set current database db.foo.find() list objects in collection foo db.foo.find( { a : 1 } ) list objects in foo where a == 1 it result of the last line evaluated; use to further iterate DBQuery.shellBatchSize = x set default number of items to display on shell exit quit the mongo shellCopy the code

Db.help () : database related help command

Example:

> db.help() DB methods: db.adminCommand(nameOrDocument) - switches to 'admin' db, and runs command [just calls db.runCommand(...)]  db.aggregate([pipeline], {options}) - performs a collectionless aggregation on this database; returns a cursor db.auth(username, password) db.cloneDatabase(fromhost) db.commandHelp(name) returns the help for the command db.copyDatabase(fromdb, todb, fromhost) db.createCollection(name, {size: ... , capped: ... , max: ... }) db.createView(name, viewOn, [{$operator: {...}}, ...] . {viewOptions}) db.createUser(userDocument) db.currentOp() displays currently executing operations in the db db.dropDatabase() db.eval() - deprecated db.fsyncLock() flush data to disk and lock server for backups db.fsyncUnlock() unlocks server following a db.fsyncLock() db.getCollection(cname) same as db['cname'] or db.cname db.getCollectionInfos([filter]) - returns a list that contains the names and options of the db's collections db.getCollectionNames() db.getLastError() - just returns the err msg string db.getLastErrorObj() - return full status object db.getLogComponents() db.getMongo() get the server connection object db.getMongo().setSlaveOk() allow queries on a replication slave server db.getName() db.getPrevError() db.getProfilingLevel() - deprecated db.getProfilingStatus() - returns if profiling is on and slow threshold db.getReplicationInfo() db.getSiblingDB(name) get the db at the same server as this one db.getWriteConcern() - returns the write concern used for any operations on this db, inherited from server object if set db.hostInfo() get details about the server's host db.isMaster() check replica primary status db.killOp(opid) kills the current operation in the db db.listCommands() lists all the db commands db.loadServerScripts() loads all the scripts in db.system.js db.logout() db.printCollectionStats() db.printReplicationInfo() db.printShardingStatus() db.printSlaveReplicationInfo() db.dropUser(username) db.repairDatabase() db.resetError() db.runCommand(cmdObj) run a database command. if cmdObj is a string, turns it into {cmdObj: 1} db.serverStatus() db.setLogLevel(level,) db.setProfilingLevel(level,slowms) 0=off 1=slow 2=all db.setWriteConcern() -  sets the write concern for writes to the db db.unsetWriteConcern() - unsets the write concern for writes to the db db.setVerboseShell(flag) display extra information in shell output db.shutdownServer() db.stats() db.version() current version of the serverCopy the code

Db. collection name. help() : collection related help command

Example:

> db.php.help() DBCollection help db.php.find().help() - show DBCursor help db.php.bulkWrite( operations, ) - bulk execute write operations, optional parameters are: w, wtimeout, j db.php.count( query = {}, ) - count the number of documents that matches the query, optional parameters are: limit, skip, hint, maxTimeMS db.php.copyTo(newColl) - duplicates collection by copying all documents to newColl; no indexes are copied. db.php.convertToCapped(maxBytes) - calls {convertToCapped:'php', size:maxBytes}} command db.php.createIndex(keypattern[,options]) db.php.createIndexes([keypatterns], ) db.php.dataSize() db.php.deleteOne( filter, ) - delete first matching document, optional parameters are: w, wtimeout, j db.php.deleteMany( filter, ) - delete all matching documents, optional parameters are: w, wtimeout, j db.php.distinct( key, query, ) - e.g. db.php.distinct( 'x' ), optional parameters are: maxTimeMS db.php.drop() drop the collection db.php.dropIndex(index) - e.g. db.php.dropIndex( "indexName" ) or db.php.dropIndex( { "indexKey" : 1 } ) db.php.dropIndexes() db.php.ensureIndex(keypattern[,options]) - DEPRECATED, use createIndex() instead db.php.explain().help() - show explain help db.php.reIndex() db.php.find([query],[fields]) - query is an optional query filter. fields is optional set of fields to return. e.g. db.php.find( {x:77} , {name:1, x:1} ) db.php.find(...) .count() db.php.find(...) .limit(n) db.php.find(...) .skip(n) db.php.find(...) .sort(...) db.php.findOne([query], [fields], [options], [readConcern]) db.php.findOneAndDelete( filter, ) - delete first matching document, optional parameters are: projection, sort, maxTimeMS db.php.findOneAndReplace( filter, replacement, ) - replace first matching document, optional parameters are: projection, sort, maxTimeMS, upsert, returnNewDocument db.php.findOneAndUpdate( filter, update, ) - update first matching document, optional parameters are: projection, sort, maxTimeMS, upsert, returnNewDocument db.php.getDB() get DB object associated with collection db.php.getPlanCache() get query plan cache associated with collection db.php.getIndexes() db.php.group( { key : ... , initial: ... , reduce : ... [, cond: ...]  } ) db.php.insert(obj) db.php.insertOne( obj, ) - insert a document, optional parameters are: w, wtimeout, j db.php.insertMany( [objects], ) - insert multiple documents, optional parameters are: w, wtimeout, j db.php.mapReduce( mapFunction , reduceFunction , ) db.php.aggregate( [pipeline], ) - performs an aggregation on a collection; returns a cursor db.php.remove(query) db.php.replaceOne( filter, replacement, ) - replace the first matching document, optional parameters are: upsert, w, wtimeout, j db.php.renameCollection( newName , ) renames the collection. db.php.runCommand( name , ) runs a db command with the given name where the first param is the collection name db.php.save(obj) db.php.stats({scale: N, indexDetails: true/false, indexDetailsKey: , indexDetailsName: }) db.php.storageSize() - includes free space allocated to this collection db.php.totalIndexSize() - size in bytes of all the indexes db.php.totalSize() - storage allocated for all data and indexes db.php.update( query, object[, upsert_bool, multi_bool] ) - instead of two flags, you can pass an object with fields: upsert, multi db.php.updateOne( filter, update, ) - update the first matching document, optional parameters are: upsert, w, wtimeout, j db.php.updateMany( filter, update, ) - update all matching documents, optional parameters are: upsert, w, wtimeout, j db.php.validate( ) - SLOW db.php.getShardVersion() - only for use with sharding db.php.getShardDistribution() - prints  statistics about data distribution in the cluster db.php.getSplitKeysForChunks( ) - calculates split points over all chunks and returns splitter function db.php.getWriteConcern() - returns the write concern used for any operations on this collection, inherited from server/db if set db.php.setWriteConcern( ) - sets the write concern for writes to the collection db.php.unsetWriteConcern( ) - unsets the write concern for writes to the collection db.php.latencyStats() - display operation latency histograms for this collectionCopy the code

Four, add, delete, change and check operation

1. Add documents

Insert ({k1:v1,k2:v2… }) : Add documents to this collection in the current database

Note the following when adding documents:

A) Documents are key-value pairs, and the data type is BSON format, which supports richer values. BSON is an extension of JSON, adding data types that JSON does not support, such as dates and floating points.

B) Add an ‘_id’ key to the ObjectID object type. The value is ObjectID.

Each document has an _ID field, and the _ID value is unique in the same collection. This field can be any type of data, and the default is an ObjectID object. ObjectID of object data: timestamp | machine | | PID counter _id key values we can input, but can’t repeat, but should pay attention to the point that when inserting data, if the value of the _id repeat will be an error

C) You can use JS code to insert documents in batches

Example:

> for(var i=1; i<=10; i++){ ... db.php.insert({'name':'xiaobai'+i,'age':i,'email':'xiaobai'+i+'@gmail.com'}) ... } WriteResult({ "nInserted" : 1 }) > db.php.find() { "_id" : ObjectId("5b931b74a39e4f4842ba36b3"), "name" : "xiaoming", "age" : 20, "email" : "[email protected]" } { "_id" : ObjectId("5b931b7ca39e4f4842ba36b4"), "name" : "xiaohong", "age" : 18, "email" : "[email protected]" } { "_id" : ObjectId("5b931dfba39e4f4842ba36b5"), "name" : "xiaobai1", "age" : 1, "email" : "[email protected]" } { "_id" : ObjectId("5b931dfba39e4f4842ba36b6"), "name" : "xiaobai2", "age" : 2, "email" : "[email protected]" } { "_id" : ObjectId("5b931dfba39e4f4842ba36b7"), "name" : "xiaobai3", "age" : 3, "email" : "[email protected]" } { "_id" : ObjectId("5b931dfba39e4f4842ba36b8"), "name" : "xiaobai4", "age" : 4, "email" : "[email protected]" } { "_id" : ObjectId("5b931dfba39e4f4842ba36b9"), "name" : "xiaobai5", "age" : 5, "email" : "[email protected]" } { "_id" : ObjectId("5b931dfba39e4f4842ba36ba"), "name" : "xiaobai6", "age" : 6, "email" : "[email protected]" } { "_id" : ObjectId("5b931dfba39e4f4842ba36bb"), "name" : "xiaobai7", "age" : 7, "email" : "[email protected]" } { "_id" : ObjectId("5b931dfba39e4f4842ba36bc"), "name" : "xiaobai8", "age" : 8, "email" : "[email protected]" } { "_id" : ObjectId("5b931dfba39e4f4842ba36bd"), "name" : "xiaobai9", "age" : 9, "email" : "[email protected]" } { "_id" : ObjectId("5b931dfba39e4f4842ba36be"), "name" : "xiaobai10", "age" : 10, "email" : "[email protected]" }Copy the code
2. Delete the document

Db. Set name. Remove {(condition)} : delete all documents in the specified set in the current database (delete all documents without condition)

Example:

> db.php.remove({age:20})
WriteResult({ "nRemoved" : 1 })
> db.php.remove({age:{'$lt':6}})
WriteResult({ "nRemoved" : 5 })
> db.php.find()
{ "_id" : ObjectId("5b931b7ca39e4f4842ba36b4"), "name" : "xiaohong", "age" : 18, "email" : "[email protected]" }
{ "_id" : ObjectId("5b931dfba39e4f4842ba36ba"), "name" : "xiaobai6", "age" : 6, "email" : "[email protected]" }
{ "_id" : ObjectId("5b931dfba39e4f4842ba36bb"), "name" : "xiaobai7", "age" : 7, "email" : "[email protected]" }
{ "_id" : ObjectId("5b931dfba39e4f4842ba36bc"), "name" : "xiaobai8", "age" : 8, "email" : "[email protected]" }
{ "_id" : ObjectId("5b931dfba39e4f4842ba36bd"), "name" : "xiaobai9", "age" : 9, "email" : "[email protected]" }
{ "_id" : ObjectId("5b931dfba39e4f4842ba36be"), "name" : "xiaobai10", "age" : 10, "email" : "[email protected]" }
Copy the code

Here we use the operator to delete documents younger than 6 from the PHP collection.

Comparison operator

The operator The effect
$gt Is greater than
$lt Less than
$gte Greater than or equal to
$lte Less than or equal to
$exists Presence or absence of
$in contains
$ne Is not equal to
$nin Does not contain

Logical operator

The operator The effect
$exists Presence or absence of
$or or
$and and
$not There is no
$mod modulus
$where location

The special $exists: true indicates that the field exists

Sort sort

operation The effect
$asc ascending
$desc Descending order
3. Update documentation

There are two ways to update a document

Method one, direct modification

Db. collection name. update({condition},{new document}) : Modifies the information about documents in the specified collection in the current database that meet the condition

Example:

> db.php.find()
{ "_id" : ObjectId("5b931b7ca39e4f4842ba36b4"), "name" : "xiaohong", "age" : 18, "email" : "[email protected]" }
> db.php.update({age:18},{name:'xiaobai5'})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.php.find()
{ "_id" : ObjectId("5b931b7ca39e4f4842ba36b4"), "name" : "xiaobai5" }
Copy the code

Db. collection. update(condition, new document, Whether to add, whether to modify multiple documents) : modifies the documents that meet the condition in the specified collection in the current database

  • Add or not: If the value is 1(true), add if no condition is met
  • Whether to modify multiple documents: If the value is 1(true), modify all documents that meet the condition

Example:

> db.php.update({age:10},{name:'xiaoli'},true,true)
WriteResult({
    "nMatched" : 0,
    "nUpserted" : 0,
    "nModified" : 0,
    "writeError" : {
        "code" : 9,
        "errmsg" : "multi update only works with $ operators"
    }
})
Copy the code

Method 2: Use a modifier

Example:

We want to change the name of the document age=6 to xiaosan and not lose the other key values

We can use modifiers

  • $inc: Add a number
  • $set: Modifies a field. If the field does not exist, add the field

Update ({condition},{modifier name :{modified key: modified new value}})

> db.php.update({age:6},{'$set':{name:'xiaosan'}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Copy the code

So if we wanted to change the document age=10 to increase the age by ten years, we could do this:

> db.php.update({age:10},{$inc:{age:10}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Copy the code
4. Query documents

Syntax: db. collection name. find({condition})

Example:

Fetch the first document in the PHP collection

> db.php.findOne()
{ "_id" : ObjectId("5b931b7ca39e4f4842ba36b4"), "name" : "xiaobai5" }
Copy the code

Fetch the PHP collection with age=6

> db.php.find({age:6})
{ "_id" : ObjectId("5b931dfba39e4f4842ba36ba"), "name" : "xiaosan", "age" : 6, "email" : "[email protected]" }
Copy the code

Select age>8 from PHP collection

> db.php.find({age:{'$gt':8}})
{ "_id" : ObjectId("5b931dfba39e4f4842ba36bd"), "name" : "xiaobai9", "age" : 9, "email" : "[email protected]" }
{ "_id" : ObjectId("5b931dfba39e4f4842ba36be"), "name" : "xiaobai10", "age" : 20, "email" : "[email protected]" }
Copy the code

Retrieve the document in the PHP collection and display only the name key

> db.php.find({},{age:1})//1 displays only age key values {"_id" : ObjectId(" 5b931b7CA39e4f4842ba36b4 ")} {"_id" : ObjectId("5b931dfba39e4f4842ba36ba"), "age" : 6 } { "_id" : ObjectId("5b931dfba39e4f4842ba36bb"), "age" : 7 } { "_id" : ObjectId("5b931dfba39e4f4842ba36bc"), "age" : 8 } { "_id" : ObjectId("5b931dfba39e4f4842ba36bd"), "age" : 9 } { "_id" : ObjectId(" 5b931DFba39e4f4842ba36be "), "age" : 20} > db.php.find({},{age:0})//1 displays {"_id" in addition to the age key. ObjectId("5b931b7ca39e4f4842ba36b4"), "name" : "xiaobai5" } { "_id" : ObjectId("5b931dfba39e4f4842ba36ba"), "name" : "xiaosan", "email" : "[email protected]" } { "_id" : ObjectId("5b931dfba39e4f4842ba36bb"), "name" : "xiaobai7", "email" : "[email protected]" } { "_id" : ObjectId("5b931dfba39e4f4842ba36bc"), "name" : "xiaobai8", "email" : "[email protected]" } { "_id" : ObjectId("5b931dfba39e4f4842ba36bd"), "name" : "xiaobai9", "email" : "[email protected]" } { "_id" : ObjectId("5b931dfba39e4f4842ba36be"), "name" : "xiaobai10", "email" : "[email protected]" }Copy the code

According to the age of (descending | ascending) to display the document

Find ().sort({age:1}) sort db by age. Set name.find ().sort({age:0}) descending by ageCopy the code

Displays the first three documents in the PHP collection

> db.php.find().limit(3)
{ "_id" : ObjectId("5b931b7ca39e4f4842ba36b4"), "name" : "xiaobai5" }
{ "_id" : ObjectId("5b931dfba39e4f4842ba36ba"), "name" : "xiaosan", "age" : 6, "email" : "[email protected]" }
{ "_id" : ObjectId("5b931dfba39e4f4842ba36bb"), "name" : "xiaobai7", "age" : 7, "email" : "[email protected]" }
Copy the code

Displays the third through fifth document in the PHP collection

> db.php.find().skip(2).limit(3)
{ "_id" : ObjectId("5b931dfba39e4f4842ba36bb"), "name" : "xiaobai7", "age" : 7, "email" : "[email protected]" }
{ "_id" : ObjectId("5b931dfba39e4f4842ba36bc"), "name" : "xiaobai8", "age" : 8, "email" : "[email protected]" }
{ "_id" : ObjectId("5b931dfba39e4f4842ba36bd"), "name" : "xiaobai9", "age" : 9, "email" : "[email protected]" }
Copy the code

Count the number of documents in the PHP collection

Db.collection name.count (): Returns how many documents are in the collectionCopy the code

V. User Management (Permission control)

1. Overview of permissions

Users in MongoDB belong to databases, and each database has its own administrator. After logging in to the database, the administrator can only operate the database to which it belongs. Note: the user created in the admin database is the super administrator and can operate any database after logging in

2. Create a user

(1) Select the database

Use Specifies the name of the database

(2) Add a user

Db.createuser (username, password, read-only)

The third parameter, “read-only”, defaults to false. The created user can read and write. If it is true, the created user can only query, but cannot modify.

Note: Before creating a user, you must create a super administrator

Example:

> use admin switched to db admin > db.createUser({user:'user', ... pwd:'passwd', ... roles:[ ... {role:'userAdminAnyDatabase', db:'admin'} ... ] . }) Successfully added user: { "user" : "user", "roles" : [ { "role" : "userAdminAnyDatabase", "db" : "admin" } ] }Copy the code
3. Verify permissions (user login)

After adding an administrator, we do the following:

(1) If you are installing as a Windows service, uninstall the service and add a -auth option when installing. Auth means to enable permission authentication

(2) If you want to start the service directly, then stop the service and restart it. Add the –auth option when starting the service. Auth means to enable permission authentication

If you do not pass the permission verification and directly operate the database, the following error message is displayed:

Error: {"$err" : "Unauthorized DB :test lock type:-1 client:127.0.0.1", "code" : 10057}Copy the code

How do I pass permission authentication

  1. Select database
  2. performdb.auth(User name, password)
4. Delete the user and change the password

Note: The created user name and password are stored in the System. Users collection in their respective databases. To delete a user, simply delete the document in the System. Users collection

5. Summary and explanation

A) Users who do not belong to the admin database cannot use database commands, such as show DBS

(b) Users in the admin database are treated as super users (that is, administrators). After authentication, administrators can read and write all databases and execute specific administrative commands.

(c) Be sure to have at least one administrator account before starting security check.

(d) The user accounts of the database are stored as documents in the System. Users collection. Users can be deleted by deleting the user account document in the System. users collection.

Indexes in MongoDB

1. Plain single-column index

Let’s test with the following code:

for(var i=0; i<200000; i++){ db.java.insert({name:'xiao'+i,age:i}) }Copy the code

First, let’s test query performance

var start=new Date()
db.java.find({name:'xiao156789'})
var end=new Date()
end-start
17510
Copy the code

Create an index for name

> db.java.ensureIndex({name:1})
{
    "createdCollectionAutomatically" : false,
    "numIndexesBefore" : 1,
    "numIndexesAfter" : 2,
    "ok" : 1
}
Copy the code

Third, executing the first part of the code again shows an order of magnitude performance improvement

EnsureIndex ({key :1}) :1 is in ascending order, -1 is in descending order

2, multiple index (compound index)

EnsureIndex ({field1:1/-1,field2:1/-1}) create a composite index for name and age. GetIndexes () Checks the created indexes

3. Sub-document index

EnsureIndex ({field.subfield:1/-1}) The following documents can be indexed as sub-documents

{name: nokia mobile phone 1, price: 12.34, SPC: {weight: 100, area: 'New York'}} {name: 'nokia phones 2, price: 42.34, SPC: {weight: 200, area:' London '}}Copy the code

Say you want to query a document whose weight=100

db.goods.find({'spc.weight':100})
Copy the code

Based on the current case, we build the sub-document index

db.net.ensureIndex({'spc.w':1})
Copy the code

4. Unique index

EnsureIndex ({name:-1},{unique:true})

5. View the index

Db. Set name. GetIndexes ()

(2) Check which index is used in this query and the status information of the query data: DB. The collection name. The find ({name: “xiao}). Explain ()

6, drop index

Filed :1/-1} Delete a single index: db. Set name dropIndex({filed:1/-1})

Drop all indexes: db.collection name.dropIndexes ()

7, rebuild index

Table after many times of modification, resulting in table file void, index file is the same, through index reconstruction, reduce index file fragment, and improve index efficiency, similar to mysql optimize table.

Mysql > optimize table syntax: optimize table name

Syntax: db.collection name.reindex ()

8. Precautions for index use

(1) When creating an index, note that 1 is used to create an index in positive order and -1 is used to create an index in reverse order

(2) Index creation will affect insert performance while improving query performance. For frequent queries, insert is less

(3) Compound index should pay attention to the order of index

(4) Creating indexes for each key does not necessarily improve performance. Indexes are not a panacea.

(5) when doing sorting work, if it is a large amount of data, you can also consider adding indexes to improve sorting performance.

Data export and export in MongoDB

Using the mongoexport

  • -h host host
  • Port – the port
  • -d Specifies the library to use
  • -o Specifies the name of the file to be exported
  • – CSV Specifies the CSV format to be exported
  • -q Filters the export
  • -f field1 Field2 Column name
  • -u username indicates the username
  • -p password, “password

Note: When using user name and password as super administrator, you can specify the port without using -port if the port is the default

(2) Import data

  • -d Database to be imported
  • -c Collection to be imported (no collection will be created by itself)
  • -type CSV /json(default)
  • -file Backup file path

For example, import JSON

/bin/mongoimport -h-port port number -d test -c goods-file./goodsall.jsonCopy the code

Import CSV

/bin/mongoimport -h -port -d test -c goods-type CSV -f goods.id,goods.name -file./goodsall.csv./bin/mongoimport -d test-c goods-type csv-f -headline -f goods.id,goods.name -file./goodsallCopy the code

9. Master/Slave replication (read/write separation)

Master-slave replication is a simple clustering technique for database synchronous backup. You can set up the master server and the slave server separately for at least two database servers. Any operation on the master server will be synchronized to the slave server.

Implementation considerations

1, in the database cluster to clearly know who is the master server, the master server only one

2. The slave server needs to know who its data source is, that is, the corresponding master service

–master is used to determine the master server –slave and –source to control the slave server

The configuration steps

(1) Start the primary server

(2) Start the slave server

(3) The client logs in to the master server

Add some data to test whether it is synchronized to the slave server. On the master server, add some documents:

The first step is for the client to log in to the master server and add some documents

Step 2, log in to the slave server to see if there is data, if there is data, success!

Mysql > select MongoDB

1. Install extensions

Note: To extend the file, download the appropriate php_mongodb. DLL file

  1. The version of PHP
  2. Thread Safe (ts)
  3. Vc a few
  4. Is PHP 32-bit or 64-bit

steps

  1. Copy the corresponding extension to the ext directory in the PHP installation directory. Note: after copying the extension, rename it to php_mongo.dll for easy management
  2. Open the php.ini file to import the extension
extension=php_mongo.dll
Copy the code
  1. Restart Apache and test using the phpInfo () function

2. For entry

  1. Connecting to the mongodb Server
$m=new MongoClient("mongodb://root:root@localhost:8888/admin"); $db=$m->selectDb("stu"); // Select the databaseCopy the code
  1. Add, delete, change and check usage

Add and delete

Notice that on the command line the “.” becomes “->” and the “{}” becomes an array

A) Add a document

$db-> PHP ->insert(array('name'=>' id ','age'=>12));Copy the code

B) Query documents

$data=$db->php->find();
Copy the code

Select * from document where age = 9;

$data=$db->php->find(array('age'=>9));
Copy the code

Select * from document where age > 9;

//db.php.find({age:{'$gt':9}})
$data=$db->php->find(array('age'=>array('$gt':9)));
Copy the code

In descending order by age:

$data=$db->php->find()->sort(array('age'=>1));
foreach($data as $v){
    echo $v['name'].'----'.$v['age'].'--'.$v['email'].'';
}
Copy the code

C) To modify the document, we directly use the modifier to complete

Change the name whose age is 8 to Li Bai:

/ / db. PHP. Update ({age: 8}, {' $set: {' name ':' li bai '}}) $db - > PHP - > update (array (' age '= > 8), array (' $set' = > array (' name '= >' li '));Copy the code

D) Delete documents

For example, delete documents with age equal to 10:

//db.php.remove({age:10})
$db->php->remove(array('age'=>10))
$data=$db->php->find()
foreach($data as $v){
    echo $v['name'].'----'.$v['age'].'--'.$v['email'].'';
}
Copy the code
  1. Store data from mysql tables in mongodb
selectDb("stu"); $conn=mysql_connect('localhost','root','root'); mysql_query('use shop'); mysql_query('set names utf8'); $sql="select * from goods"; $res=mysql_query($sql); while($row=mysql_fetch_assoc($res)){ $db->goods->insert($row); } echo 'ok';Copy the code