1. About MongoDB
MongoDB is a cross-platform NoSQL document type database that holds data in the form of Key_value key-value pairs.
NoSQL (not only SQL) database, which refers to a non-relational database.
Features of the 1.1 NoSQL database
L no pre-defined mode required
There is no need to define the data schema beforehand and to predefine the table structure. Each record in the data may have different properties and formatting. When inserting data, it is not necessary to pre-define their patterns.
L No shared architecture
A fully shared schema relative to the storage area network where all the data is stored. NoSQL often divides the data and stores it on each local server. Because the performance of reading data from a local disk tends to be better than the performance of reading data over a network, it improves the performance of the system.
L Elastic Expandable
You can dynamically add or delete nodes while the system is running. No maintenance is required and data can be migrated automatically.
L Partitioning
Rather than storing data at the same node, a NoSQL database needs to partition the data and spread the records across multiple nodes. It is usually partitioned and replicated at the same time. This improves both parallel performance and guarantees that there is no single point of failure.
L Asynchronous Replication
Unlike RAID storage systems, replication in NoSQL is often a log-based asynchronous replication. In this way, the data can be written to a node as soon as possible without being delayed by the network transmission. The disadvantage is that consistency is not always guaranteed, and a small amount of data may be lost in the event of a failure.
L BASE
The NoSQL database guarantees a base feature relative to the rigorous acid characteristics of the transaction. Base is the final consistency and soft transaction.
Classification of 1.2 NoSQL databases
Classification |
Examples Example |
Typical application Scenarios |
Data model |
Advantages |
Disadvantages |
Key value (Key-value) |
Tokyo cabinet/tyrant, Redis, Voldemort, Oracle BDB |
Content caching, which is used primarily for high-access loads that handle large amounts of data, for some log systems, and so on. |
Key-value pairs that point to value, usually with hash table |
Fast Search Speed |
Data is unstructured and is usually used only as a string or binary data |
Column Store Database |
Cassandra, HBase, Riak |
Distributed File Systems |
To store the same column of data in a clustered type |
Find Fast, scalable, and easily distributed extensions |
function relative limitation |
document Type database |
< P align= "left" >couchdb, MongoDb |
web application (similar to Key-value, Value is structured, but the database is able to understand the contents of value) |
key-value corresponding key-value pairs, Value is structured data |
data structure requirements are not strict, table structure is variable, need not like relational database need to pre-define table structure |
query performance is not high, and the lack of unified query syntax. |
Graph Database (graph) |
Neo4j, Infogrid, Infinite Graph |
Social networks, referral systems, and more. Focus on building a relationship map |
Graph structure |
Using graph structure correlation algorithm. such as shortest path addressing, N-degree relationship lookup, etc. |
Many times need to calculate the entire graph to get the information needed, and this structure is not very good for the distributed cluster scheme. |
1.3 MongoDB Database Features
The MongoDB database has the following features:
L Cross-platform, support language is numerous
L Mode free
L Support File storage
L easy to scale horizontally
L Replication Set mechanism
L Multilevel Index
L for collection Storage
L Rich Query statements
In combination with these features, MongoDB is suitable for Internet applications with large data volumes, high concurrency, and weak transactions.
2. MongoDB Installation
Here is the main introduction of the installation under the Windows platform (other platform installation please the official download the corresponding installation media).
2.1 Downloading the installation media
MongoDB as follows: Https://www.mongodb.org/downloads
Download the version under the corresponding Windows platform.
Mongodbvue (visualization tool): http://www.mongovue.com/downloads/
2.2 Installation
Once the download is complete, click Install directly.
2.2.1 Adding MongoDB to an environment variable
The path to the bin directory of the MongoDB installation directory will be as follows: C:\Program Files\mongodb\server\3.0\bin
Add to the environment variable path. To detect whether to add success, you can enter mongo–version on the command line to view the version number of the installed MongoDB, as shown in the following:
2.2.2 Start MongoDB
Before you start MongoDB, you need to specify the corresponding data (i.e. datastore) directory, log directory, and directory structure as shown:
Then enter the following command at the command line:
C:\windows\system32>mongod--dbpath D:\MangoDB\Data--logpath d:\mangodb\log\mongodb.log–logappend
The command mainly specifies a data store directory and a log directory for MongoDB, which is entered in the browser:
http://localhost:27017
When you see the following, the service is started:
It looks like you is trying to access MongoDB over HTTP on the native driver port.
If the command window is closed, the database service is stopped. However, there is a problem, each time you open the service, you need to enter this line of command, it will be very troublesome. We have two ways to solve this problem, as follows:
L Save the above command as a bat file and click it each time you start the service (i.e. the start file shown in)
L Add MongoDB to the service and start as a service as follows:
On the command line, enter the following command:
C:\windows\system32>mongod--dbpath D:\MangoDB\Data--logpath D:\MangoDB\Log\mongodb.log--install--servicename " MongoDB "
In the command line, enter: Net start MongoDB
The results are as follows:
Enter: net stop MongoDB to stop the service.
3. MongoDB Data Model
MongoDB is a document-based database for collection storage, and its basic concepts are different from the common relational database.
3.1 Documentation
The document is the core concept of MongoDB, which is essentially a kind of JSON-bjson-formatted data.
Bson is the addition of some new data types based on JSON, including dates, Int32,int64, and so on.
Bson is composed of key-value pairs, which has the characteristics of light weight, ergodic and high efficiency.
3.2 Integrated
Putting together a set of related documents makes up a collection.
A document is equivalent to a piece of information in a relational database, and a collection is equivalent to a table in a relational database.
3.3 Database
Multiple documents make up a collection, and multiple collections form a database. A MongoDB sample can host multiple databases, each with independent permissions.
3.4 Data type 3.4.1 Basic data type
Null: null or non-existent field
Boolean: True or False
Numeric type: only Int32 supported , Int64 , double
String:
Binary data: You can save a string of any byte
Regular expressions: used primarily for queries.
For example: {name:/olive/} , name field contains olive
{name:/olive/i} , name field contains olive , and is case- insensitive
{name:/^olive/i},name field to Olive start with a case insensitive
Js Code
3.4.2 Date Dates
MongoDB in the date is a 64-bit integer
When MongoDB stores time, first translates to UTC time.
3.4.3 Timestamp
Timestamp only for MongoDB internal use, to record the detail time of the operation, not related to the date type
3.4.4 Objectid
The Objectid consists of 24 hexadecimal characters, each of which stores two hexadecimal digits, which requires a total of 12 bytes of storage space.
3.4.5 Embedded Documents
The document is the value of the key, called an inline document. Embedded documents make it more natural to organize data without storing it as a key-value pair in a flat structure.
Example:
user={"name": "Olive","address": {"province": "Henan", "City": "Zhengzhou"}}
4. MongoDB Data Update
The example here is primarily a demonstration using the Python language.
To introduce the driver of MongoDB corresponding Python, first install the Pymongo package, enter in the command line: Pip install Pymongo. Referenced in the code after the installation is complete.
To create a link to a database:
#-*-Conding:utf-8-*-
Pymongo
Sys
Reload (SYS)
Sys.setdefaultencoding (' Utf-8 ')
conn = Pymongo. Mongoclient (' localhost ', 27017)
DB = conn. mdb//Creating an MDB database
DT = db.users//Create the Users data table
After the creation is complete, you can open Mongovue to view the database that you have created, as shown in the data table:
4.1 Data Insertion 4.1.1 Insert
The Insert function can only work on a collection, and if the collection does not exist, the database service is created automatically. If you do not specify a _id field when inserting, the field is added automatically.
#insert
User0 = {' name ': ' Olive ', ' sex ': ' Male ', ' age ': 21}
Dt.insert (USER0)
User1 = {' name ': ' Tom ', ' sex ': ' Female ', ' Age ': 24}
Dt.insert (User1)
User2 = {' name ': ' Jack ', ' sex ': ' Male ', ' age ': 25}
Dt.insert (User2)
User3 = {' name ': ' Kite ', ' sex ': ' Male ', ' age ': 20}
Dt.insert (User3)
In Mongovue view the inserted data as shown in:
Alternatively, you can pass in a list parameter to the Insert method, as follows:
Dt.insert ([{' Name ': ' Kobe ', ' Age ': "37},{' name ': ' Jim ', ' Age ': 30}])
Look at Mongovue again, as shown (add 2 data):
4.1.2 Insert_many ()
If you want to insert data in large quantities, you can also use the Insert_many () method, as follows:
Users = [{' Name ': ' Olive ' +str (i)} for i in xrange (101)]
Dt.insert_many (Users)
4.2 Data Updates
To modify a record within a cluster:
Dt.update (filter, Update_field, Upsert, Multi)
Query criteria for Filter:update
Update_field: field to update, update value (similar to set in SQL statement)
Upsert: If no record of update exists, true is insert, false is not inserted, default is False
Muti: Detect multiple data, if true, update all data, default to False to update only one piece of data
Dt.update ({' name ': ' Olive '},{' $set ': {' age ': 100}})
$set: update the specified field value
Usage: {$set: {Field:value}}
$unset : Delete the specified field
Usage: {$unset: {field:1}}
$inc : Updates the value of the specified field to the specified field +value
Usage: {$inc: {field:value}
4.3 Data deletion
5. MongoDB Data Query 5.1 find () 5.1.1 default no parameter or find ({}) queries all data.
Find ({},{})
First {} put where conditions a second {} specify those columns to display and not display (0 indicates that 1 is not displayed indicates display)
5.1.2 Queries with parameters
user = Dt.find ({' name ': ' Olive '})
Results such as:
5.1.3 Query operator use (and query): $LT, $lte, $gt, $gte, $ne
user = Dt.find ({' name ': ' Olive ', ' age ': {' $lt ': 90}})
5.1.4 or query
User =dt.find ({' $or ': [{' Name ': ' Olive '},{' age ': {' $lt ': 50}}]})
5.1.5 query for a field in the embedded document (you need to use the. Number operator):
Insert a document with an inline field first
Dt.insert_one ({' name ': ' 111 ', ' address ': {' princience ': ' Beijing ', ' City ': ' Beijing '}})
Examples are as follows:
user = Dt.find ({' address.city ': ' Beijing '})
5.1.6 in (NIN) query
User =dt.find ({' name ': {' $in ': [' Olive ', ' Tom ', ' Jack ']})
User =dt.find ({' name ': {' $nin ': [' Olive ', ' Tom ', ' Jack ']})
5.1.7 to sort the results of the query:
user = Dt.find (). Sort (' name ', Pymongo. Ascending)//single field
user = Dt.find (). sort ([' Name ', Pymongo. Ascending), (' Age ', Pymongo. Descending)])//multiple fields
5.1.8 like query (MongoDB supports regular expressions/xxx//^xxx/starts with XXX)
User =dt.find ({"Name":/"Olive"/})
5.2 Find_one ()
Find only one piece of information.
Example:
User =dt.find_one ({' name ': ' Olive '})
print user[' name ']
The results are as follows:
"Olive"
A quick-to-use article about MongoDB, written here basically ended, hoping to get a quick start with MongoDB's friends to help. Examples of this article are written in Python+mongodb, of course, MongoDB official also has the adaptation to other languages, here just for the convenience of demonstration. Interested friends can go to MongoDB's official website to see, in order to further research.
MongoDB quickly get started