MongoDB Learning Summary (i)

Source: Internet
Author: User
Tags mongodb sharding mongodump mongorestore

1. Download and decompress mongodb and configure environment variables
tar -zxvf mongodb-linux-x86_64-rhel62-3.2.7.tgz
export PATH = <mongodb-install-directory> / bin: $ PATH

2. Create a data save directory
mkdir -p / data / db

3.mongodb start
./mongod // Start by default
./mongod --dbpath = / data / db // Start mongodb and specify the data retention directory
./mongod --dbpath = / data / db --rest // Start mongodb and start the web user interface (http: // ip: 28017)

4. Use the local client to close mongodb (kill -9 is prohibited)
./mongod
use admin
db.shutdownServer () // Shut down by default
db.shutdownServer ({force: true}) // Forcibly shut down
db.shutdownServer ({force: true, timeoutsec: 5}) // Specify the timeout time, shut down the server within the timeout time

5. Basic database operation commands
mongodb: // admin: [email protected] / test // Log in to the specified database using the username and password
use DATABASE_NAME // Create a database
show dbs // View all databases
db.dropDatabase () // Delete the database
db.collection.drop // Delete collection
db.col.insert (document) // Insert some data into the runoob database
db.col.save (document) // Similar to the insert () method, if _id is specified, the data of this _id will be updated.
db.col.remove ({"age": "255"}, 1) // Delete a piece of data
db.col.update ({"name": "hello"}, {$ set: {"age": "255"}}) // Update data
db.col.update ({"age": {$ eq: "24"}}, {$ set: {"name": "hehe"}}); // Update the specified document
db.col.save (<document>, {writeConcern: <document>}) // Replace the existing document with the incoming document, parameter writeConcern: optional, the level of exception thrown.
db.col.find () // Query data
db.col.find (). pretty () // Format query data
db.col.find ({"name": "hehe", "_ id": "abc"}) // AND condition query
db.col.find ({$ or: [{"name": "hehe"}, {"_ id": "abc"}]}) // OR query

6.mongodb conditional operator
(>) Greater than-$ gt db.col.find ({"num": {$ gt: 3}})
(<) Less than-$ lt db.col.find ({"num": {$ lt: 3}})
(> =) Greater than or equal to-$ gte db.col.find ({"num": {$ gte: 3}})
(<=) Less than or equal to-$ lte db.col.find ({"num": {$ lte: 3}})

7. The $ type operator in mongodb
Double 1 db.col.find ({"num": {$ type: 1}})
String 2
Object 3
Array 4
Binary data 5
Undefined 6 is obsolete.
Object id 7
Boolean 8
Date 9
Null 10
Regular Expression 11
JavaScript 13
Symbol 14
JavaScript (with scope) 15
32-bit integer 16
Timestamp 17
64-bit integer 18
Min key 255 Query with -1.
Max key 127

7. Limit and Skip methods in mongodb
db.col.find (). limit (1) // Read the specified number of data records
db.col.find (). skip (1) // Skip the specified amount of data
db.col.find (). limit (10) .skip (10 * 0) // Page query the first page

8.mongodb sort () method
db.col.find (). sort ({"num": 1}) // 1 is sorted in ascending order
db.col.find (). sort ({"num":-1}) //-1 is used to sort in descending order

9. MongoDB uses the ensureIndex () method to create the index.
db.col.ensureIndex ({"num": 1}) // 1 Create an index in ascending order for the specified
db.col.ensureIndex ({"num": 1}) //-1 specifies the index to be created in descending order
ensureIndex () receives optional parameters. The list of optional parameters is as follows:
Parameter Type Description
background Boolean The index building process will block other database operations. The background can be specified to create the index in the background, that is, the optional parameter "background" is added. The default value of "background" is false.
unique Boolean Whether the index created is unique. Specify true to create a unique index. The default value is false.
name string The name of the index. If not specified, MongoDB generates an index name by connecting the field names and sort order of the index.
dropDups Boolean Whether to delete duplicate records when creating a unique index. Specify true to create a unique index. The default value is false.
sparse Boolean does not enable indexing on field data that does not exist in the document; this parameter needs special attention. If set to true, documents that do not contain the corresponding field will not be queried in the index field. The default value is false.
expireAfterSeconds integer Specify a value in seconds to complete the TTL setting and set the set survival time.
v index version The index version number. The default index version depends on the version that mongod runs when creating the index.
weights document Index weight value, with a value between 1 and 99,999, indicating the index's score weight relative to other index fields.
default_language string For text indexing, this parameter determines the list of stop words and the rules for stems and word generators. The default is English
language_override string For text indexing, this parameter specifies the field names contained in the document. The language overrides the default language, and the default value is language.

10. MongoDB uses the aggregate () aggregation method, which is mainly used to process data (such as statistical average, summation, etc.) and return the calculated data results.
db.col.aggregate ([{$ group: {_id: "$ num", count: {$ sum: 1}}}])
Aggregated expression:
Expression Description Example
$ sum calculates the sum. db.col.aggregate ([{$ group: {_ id: "$ by_user", num_tutorial: {$ sum: "$ likes"}}}])
$ avg Calculate average db.col.aggregate ([{$ group: {_ id: "$ by_user", num_tutorial: {$ avg: "$ likes"}}}])
$ min Get the minimum value corresponding to all documents in the collection. db.col.aggregate ([{$ group: {_ id: "$ by_user", num_tutorial: {$ min: "$ likes"}}}])
$ max Get the maximum value corresponding to all documents in the collection. db.col.aggregate ([{$ group: {_ id: "$ by_user", num_tutorial: {$ max: "$ likes"}}}])
$ push inserts values into an array in the resulting document. db.col.aggregate ([{$ group: {_ id: "$ by_user", url: {$ push: "$ url"}}}])
$ addToSet inserts values into an array in the result document, but does not Create a copy. db.col.aggregate ([{$ group: {_ id: "$ by_user", url: {$ addToSet: "$ url"}}}])
$ first gets the first document data according to the order of resource documents. db.col.aggregate ([{$ group: {_ id: "$ by_user", first_url: {$ first: "$ url"}}}])
$ last gets the last document data according to the order of resource documents db.col.aggregate ([{$ group: {_ id: "$ by_user", last_url: {$ last: "$ url"}}}])
Several operations commonly used in the aggregation framework:
$ project: modify the structure of the input document. It can be used to rename, add or delete fields, and can also be used to create calculation results and nested documents. db.col.aggregate ({$ project: {"_ id": 0, "title": 1, "tags": 1}})
$ match: Used to filter data and output only documents that meet the conditions. $ match uses MongoDB's standard query operations. db.col.aggregate ([{$ match: {likes: {$ lte: 100}}}, {$ group: {_ id: "$ title", count: {"$ sum": "$ likes"}}} ])
$ limit: Used to limit the number of documents returned by the MongoDB aggregation pipeline. db.col.aggregate ({$ limit: 2})
$ skip: Skip the specified number of documents in the aggregation pipeline and return the remaining documents. db.col.aggregate ({$ skip: 1})
$ unwind: Split an array type field in the document into multiple items, each containing a value in the array.
$ group: Group the documents in the collection, which can be used for statistical results.
$ sort: Sort input documents and output.
$ geoNear: Output ordered documents close to a certain geographic location.

11.mongodb replication (copy set)
Specify the --replSet option to start mongodb mongod --port 27017 --dbpath "/ data / db" --replSet rs0
Start a new copy set rs.initiate () ### Client use command
View the configuration of the replica set rs.conf ()
View replica set status rs.status ()
Add a member of the replica set rs.add (HOST_NAME: PORT)
Determine whether the currently running Mongo service is the master node db.isMaster ()

12.mongodb sharding
The main components in the distribution of sharded cluster structure in MongoDB:
Shard: used to store actual data blocks. In the actual production environment, a shard server role can be assumed by several machines and a relica set to prevent single point of failure of the host
Config Server: mongod instance, stores the entire ClusterMetadata, including chunk information.
Query Routers: front-end routers, which clients access, and make the entire cluster look like a single database, front-end applications can be used transparently
Step 1: Start Shard Server
mkdir -p / data / mongoDB / shard / s0
mkdir -p / data / mongoDB / shard / s1
mkdir -p / data / mongoDB / shard / s2
mkdir -p / data / mongoDB / shard / s3
mkdir -p / data / mongoDB / shard / log
/usr/local/mongodb/mongodb-linux-x86_64-rhel62-3.2.7/bin/mongod --port 27020 --dbpath = / data / mongoDB / shard / s0 --logpath = / data / mongoDB / shard / log /s0.log --logappend --fork
/usr/local/mongodb/mongodb-linux-x86_64-rhel62-3.2.7/bin/mongod --port 27021 --dbpath = / data / mongoDB / shard / s1 --logpath = / data / mongoDB / shard / log /s1.log --logappend --fork
/usr/local/mongodb/mongodb-linux-x86_64-rhel62-3.2.7/bin/mongod --port 27022 --dbpath = / data / mongoDB / shard / s2 --logpath = / data / mongoDB / shard / log /s2.log --logappend --fork
/usr/local/mongodb/mongodb-linux-x86_64-rhel62-3.2.7/bin/mongod --port 27023 --dbpath = / data / mongoDB / shard / s3 --logpath = / data / mongoDB / shard / log /s3.log --logappend --fork
Step 2: Start Config Server
mkdir -p / data / mongoDB / shard / config
/usr/local/mongodb/mongodb-linux-x86_64-rhel62-3.2.7/bin/mongod --port 27100 --dbpath = / data / mongoDB / shard / config --logpath = / data / mongoDB / shard / log /config.log --logappend --fork
Step 3: Start Route Process
/usr/local/mongodb/mongodb-linux-x86_64-rhel62-3.2.7/bin/mongos --port 40000 --configdb localhost: 27100 --fork --logpath = / data / mongoDB / shard / log / route. log --chunkSize 500
Step 4: Configure Sharding
Next, we use MongoDB Shell to log in to mongos and add Shard nodes
/usr/local/mongodb/mongodb-linux-x86_64-rhel62-3.2.7/bin/mongo admin --port 40000
mongos> db.runCommand ({addshard: "localhost: 27020"})
mongos> db.runCommand ({addshard: "localhost: 27021"})
mongos> db.runCommand ({addshard: "localhost: 27022"})
mongos> db.runCommand ({addshard: "localhost: 27023"})
mongos> db.runCommand ({enablesharding: "test"}) #### Set the database for shard storage
mongos> db.runCommand ({shardcollection: "test.log", key: {id: 1, time: 1}})
Step 5: Without much change in the program code, directly connect the database to the interface 40000, just like the ordinary mongo database

13. MongoDB data backup and data recovery
The mongodump command script syntax is as follows:
./bin/mongodump -h 127.0.0.1:27020 -d test -o / data / dump
-h: server address where mongdb is located, for example: 127.0.0.1, of course, you can also specify the port number: 127.0.0.1:27017
-d: database instance to be backed up, for example: test
-o: The storage location of the backup data, for example: / data / dump. Of course, this directory needs to be established in advance. After the backup is completed, the system automatically creates a test directory under the dump directory. This directory stores the backup data of the database instance.
The mongorestore command script syntax is as follows:
./bin/mongorestore --host = 127.0.0.1 --port = 27020 --db = test --dir = / data / dump / test --drop
./bin/mongorestore --help
-h: server address where mongodb is located
-d: need to restore the database instance, for example: test
--dir: the location of the backup data, for example: / data / dump / test
--drop: When restoring, delete the current data first, and then restore the backup data. In other words, after recovery, the data added and modified after backup will be deleted, use with caution!

14. Mongodb provides two commands, mongostat and mongotop, to monitor the operation of mongodb.
./bin/mongostat --host = 127.0.0.1 --port = 27020
./bin/mongotop --host = 127.0.0.1 --port = 27020 3

 

Reference: http://www.runoob.com/mongodb/mongodb-tutorial.html

mongodb learning summary (1)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.