MongoDB Learning Summary

Source: Internet
Author: User
Tags failover mongodb save mongodb server

Start the corresponding SERVER:CD: Mongod--dbpath db Path to the Mangodb installation root directory
To create the MANGODB service:
Mongod.exe--logpath d:/mongodb/logs/mongodb.log--logappend--dbpath d:/mongodb/db--directoryperdb--serviceName Mongodb-install
Add three commands: (You must run CMD as an administrator, and then execute the following command)

Start Mongodb:net start MongoDB
Stop Mongodb:net Stop MongoDB
Delete MONGODB:SC Delete MongoDB

Create Database
Use database_name
Use MyDB
Check the currently selected database
Db
Check all databases
Show DBS

Create a Collection
Createconllection (name,options)
option has the following focus
Capped Boolean (optional) If true, the CAP collection is enabled. A cap set is a fixed-size collection that automatically overwrites the oldest entry when he reaches the maximum size. If true, you need to specify the dimension parameter as well.
Autoindexid Boolean (optional) If true, the default value for the auto-create index _id field is false.
Size number (optional) specifies the maximum size of the byte cap collection. If the cap is true, you must specify this field.
Max Number (optional) specifies the maximum allowed file size for the capping collection.
Show Conllections
In MongoDB, you do not need to create a collection. When inserting some files MongoDB show automatically creates the collection.

MongoDB supports a list of many data types as given below:

String: This is the most commonly used data type to store data. The string in MongoDB must be a valid UTF-8.
Integer: This type is used to store a numeric value. The integer can be either 32-bit or 64-bit, depending on your server.
Boolean: This type is used to store a Boolean value (True/false).
Double: This type is used to store floating-point values.
Min/max keys: This type is used to compare the lowest and highest values of the Bson element.
Arrays: Use this type of array or list or multiple values to store to a key.
Timestamp: Timestamp. This makes it easy to record when the file has been modified or added.
Object: This data type is used for embedded files.
Null: This type is used to store a null value.
Symbol: This data type is used for the same string, but it is usually reserved for languages of a particular symbol type.
Date: This data type is used to store the UNIX time format for the current date or time. You can specify your own date and time, date and year, month, day to create an object.
Object ID: This data type is used to store the document ID.
Binary data: This data type is used to store binaries.
Code: This data type is used to store JavaScript code in the document.
Regular expression: This data type is used to store regular expressions

Insert data: Db.collection.insert () or Db.collection.save ()
Db.mycol.insert ({title: ' 123 ', Name: ' Tony '})
Insert multiple lines at once:
Db.mycol.insert ([{title: ' 123 ', Name: ' Tony '},{title: ' 456 ', Name: ' Hans '}])

Inquire
Db.database.find () display of unformatted data
Db.database.find (). Pretty () Display formatted data
FindOne () returns a file

RDBMS WHERE clause and MongoDB equivalent statement

To query the file based on some conditions, you can use the following actions


Operation

Grammar

Example

RDBMS equivalent

equality {<key>:<value>} db.mycol.find ({"By": "Tutorials Yiibai"}). Pretty () where by = ' Tutorials Yiibai '
Less Than {<key>:{$lt: <value>}} db.mycol.find ({"likes": {$lt:]}). Pretty () where likes < 50
Less Than Equals {<key>:{$lte: <value>}} db.mycol.find ({"likes": {$lte:]}). Pretty () where likes <= 50
Greater Than {<key>:{$gt: <value>}} db.mycol.find ({"likes": {$gt:]}). Pretty () where likes > 50
Greater Than Equals {<key>:{$gte: <value>}} db.mycol.find ({"likes": {$gte:]}). Pretty () where likes >= 50
Not Equals {<key>:{$ne: <value>}} db.mycol.find ({"likes": {$ne:]}). Pretty () where likes! = 50

and in MongoDB usage

Grammar:

In the Find () method, if you detach ', ' through multiple keys, then MongoDB handles the and condition. The and basic syntax is as follows:
>db.mycol.find ({key1:value1, key2:value2}). Pretty ()
MongoDB in or

Grammar:

To query a file based on the or condition, you need to use the $or keyword. The OR basic syntax is as follows:
>db.mycol.find (
{
$or: [
{key1:value1}, {key2:value2}
]
}
). Pretty ()

Use with AND and OR
The files shown below will show images with a file greater than 100, with the title "MongoDB Overview" or "Yiibai". Equivalent to the SQL WHERE clause for ' where likes>10 and (by = ' Yiibai ' OR title = ' MongoDB Overview ') '
>db.mycol.find ("likes": {$gt: ten}, $or: [{"By": "Yiibai"}, {"title": "MongoDB Overview"}]}). Pretty ()

To modify the syntax:
The basic syntax for the update () method is as follows
Db. Collection_name.update (Selectioin_criteria, Updated_data)
MongoDB Save () method
The Save () method replaces the existing document and the Save () method through the new document
Replace must ensure all lengths are consistent or replace fails

Query the corresponding field method:
Db. Collection_name.find ({},{key:1})
Note that the _id field is always displayed in the Execute Find () method, and if you do not want this field, you need to set it to 0
The Limit () method queries several records for incoming numbers
Db. Collection_name.find (). Limit (number)
Skip () skips a few records
Db. Collection_name.find (). Skip (number)

Sort () method ordering
The basic syntax for the sort () method is 1 for ascending order, 1 for descending order.
Db. Collection_name.find (). Sort ({key:1})


If you do not specify a sort priority, then the sort () method displays the document in ascending order.
The query efficiency of the resolution supported by the index. If there is no index, MongoDB must scan the collection of each document to select the query statements that match those documents. The efficiency of this scanning is very low, it will require the processing of large amount of data mongod.
An index is a special data structure that stores a small subset of data that is set in an easy-to-traverse form. The index stores the values of a specific field or set of fields, arranged in a field of the value specified in the index.
Ensureindex () method to create an index
To create an index, you need to use the Ensureindex () method of MongoDB.
Grammar:
The basic syntax for the Ensureindex () method is as follows
Db. Collection_name.ensureindex ({key:1})
Db.mycol.ensureIndex ({"title": 1})
In the Ensureindex () method, you can create an index on multiple fields by multiple fields.
Db.mycol.ensureIndex ({"title": 1, "description":-1})

The Ensureindex () method can also accept a list of options (optional), with the list given below:

Background Boolean to index in the background so that indexing does not block other database activity. Specifies true to establish in the background. The default value is False.
The unique Boolean creates a unique index so that the collection does not accept Insert index keys or keys that match existing values stored in the index document. Specifies to create a unique index. The default value is False.
Name of the string index. If not specified, MongoDB generates an index name for the index field and the sort order concatenation.
Dropdups Boolean creates a unique indexed field that may have duplicates. MongoDB index only the first occurrence of a key, all files removed from the collection contain subsequent occurrences of that key. Specifies to create a unique index. The default value is False.
Sparse Boolean If true, the reference refers only to the field specified by the document. These indexes use less space, but in some cases, in particular, a variety of different manifestations. The default value is False.
Expireafterseconds integer specifies a value in seconds for the TTL control for how long the MongoDB document remains in this collection.
The version number of V index version. The default index version depends on the version of MongoDB run when the index is created.
The weights document weight is a number in the range from 1 to 99999, representing the value of the field, relative to the other index field fractions.
Default_language string for a text index, determines the language of the Stop word and the list of stemmers and markup generation rules. The default value is 中文版.
Language_override string for a text index, the specified name is included in the document that overrides the default language in the Language field. The default value is language.


Data logging and calculation results are returned during the aggregation operation. Aggregation Operations group values from multiple documents, and can perform various operations, grouping data to return a single result. The SQL COUNT (*) and group by are equivalent to the aggregation of MongoDB.
Aggregate () method
For aggregation in MongoDB, the aggregate () method should be used.
Grammar:
The basic syntax for the aggregate () method is as follows
Db. Collection_name.aggregate (aggregate_operation)
$sum summarizes the values defined from all the files in the collection. Db.mycol.aggregate ([{$group: {_id: "$by _user", num_tutorial: {$sum: "$likes"}}])
$avg the average calculated from all the given values in all document collections. Db.mycol.aggregate ([{$group: {_id: "$by _user", num_tutorial: {$avg: "$likes"}}])
$min gets the smallest corresponding value in all the files in the collection. Db.mycol.aggregate ([{$group: {_id: "$by _user", num_tutorial: {$min: "$likes"}}])
$max gets the maximum of the corresponding values in all the files in the collection. Db.mycol.aggregate ([{$group: {_id: "$by _user", num_tutorial: {$max: "$likes"}}])
$push values are inserted into an array-generated document. Db.mycol.aggregate ([{$group: {_id: "$by _user", url: {$push: "$url"}}])
$addToSet value is inserted into the resulting document in an array, but duplicates are not created. Db.mycol.aggregate ([{$group: {_id: "$by _user", url: {$addToSet: "$url"}}])
$first the first document that gets from the source document according to the grouping. Typically, this makes sense, along with some previous applications such as "$sort"-stage. Db.mycol.aggregate ([{$group: {_id: "$by _user", First_url: {$first: "$url"}}])
$last get the Final document from the source document according to the grouping. Usually, this makes sense, along with some previous applications such as "$sort"-stage. Db.mycol.aggregate ([{$group: {_id: "$by _user", Last_url: {$last: "$url"}}])

Piping Concepts

The UNIX command shell pipeline refers to the possibility of some inputs and outputs performing operations as input to the next command. The MongoDB aggregation framework also supports the same concept. There is a set of possible stages, each of which is a set of documents as input, and produces a result set of files (or eventually generated JSON documents at the end of the pipeline). And then again to be used for the next stage and so on.

A possible phase aggregation framework is as follows:
$project: Used to select some specific fields from the collection.
$match: This is a filtering operation, so you can reduce the amount of input for the given document as the next stage.
$group: As discussed above, this is not an actual aggregation.
$sort: Sort files.
$skip: With this it is possible to skip forward a given number of documents in the list of files.
$limit: This limits the number of documents to see the given number starting at the current position
$unwind: This is used to close the position of the document using an array. When using an array, the data is a pre-joinded, and once again there are individual files, this operation will be canceled. Therefore, this stage, the number will increase the next stage of the document.

Replication is the process of synchronizing data across multiple servers. Replication provides redundancy and increases data availability with multiple copies of data on different database servers, replicating the loss of protecting databases from a single server. Replication can also allow recovery of hardware failures and service outages. Additional copies of the data, you can dedicate one?? To disaster recovery, reporting, or backup.

Why do you want to copy?
To keep your data safe
High (24*7) data availability
Disaster recovery
Maintenance without downtime (e.g. backup, index rebuild, compaction)
Read scaling (extra copy read)
Replica sets are transparent to applications

How replication works in MongoDB
MongoDB uses replica sets to achieve replication. A replica set is a set of Mongod instances that host the same data set. A node in the replica that receives all the write operations from the master node. In all other cases, the secondary nodes are applied from the main operation so that they have the same data set. A replica set can have only one master node.
1 A replica set is two or more nodes in a group (typically at least 3 nodes are required).
2 setting a node in a replica is the primary node and the remaining nodes are secondary.
3 Copy all data from the primary to the secondary node.
4 when automatic failover or repair, select the primary establishment, and select the new master node.
5 After the failed node is restored, the replica set and the artwork are added as secondary nodes.
MongoDB replication is a typical figure shown in a client application that is always associated with the primary node and the master node and then replicates the data to a level two node.
Replica set Features
• N nodes of a cluster
• Any node can be the primary
• All write operations are the main
• Automatic failover
• Automatic recovery
• The main consensus choice

Set up a replica set

In this tutorial, we convert the Mongod instance to a separate replica set. To convert to a replica setting, follow these steps:
• Turn off the MongoDB server that is already running.

Now start the MONGODB server by specifying the--replset option. --replset basic syntax is as follows:
Mongod--port "Port"--dbpath "Your_db_data_path"--replset "Replica_set_instance_name"

Example
Mongod--port 27017--dbpath "D:set upmongodbdata"--replset rs0

It launches a Mongod instance name of Rs0 with a port of 27017. Start command Prompt rs.initiate () and connect to this Mongod instance. The Mongod client executes the command Rs.initiate () to start a new replica set. To check the configuration of the replica set, execute command rs.conf (). To check the status of the copy sete Execute command: Rs.status ().

To add a member to a replica set

Adds a member to the replica set and launches the Mongod instance on multiple machines. Now start a Mongod client and issue the command Rs.add ().

Suppose the name of the Mongod instance is mongod1.net it runs on port 27017. In this case, the command executed to the replica set Rs.add () on the Mongod client. Rs.add ("mongod1.net:27017")

You can add Mongod instance replica settings only if you are connected to the master node. To check whether the connection to the primary or MONGO client does not execute the command Db.ismaster ().

MongoDB Learning Summary

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.