MongoDB Quick Start

Source: Internet
Author: User
Tags mdb database mongodb example mongodb version

MongoDB Quick Start
1. MongoDB Introduction

MongoDB is a cross-platform NoSQL document-type database that stores data in the form of Key_Value pairs.

NoSQL (not only SQL) databases generally refer to non-relational databases.

1.1 features of NoSQL Databases

LNo pre-defined mode is required

You do not need to define the data mode in advance to predefine the table structure. Each record in the data may have different attributes and formats. When inserting data, you do not need to define their modes in advance.

LNo shared Architecture

Compared to the fully-shared architecture in the network where all data is stored. NoSQL stores data on local servers. Because the performance of reading data from a local disk is often better than that of reading data through network transmission, thus improving the system performance.

LElastic and scalable

You can dynamically add or delete nodes when the system is running. Data can be automatically migrated without downtime and maintenance.

LPartition

Compared to storing data on the same node, NoSQL databases need to partition data and distribute records on multiple nodes. In addition, replication is also required for partitions. This not only improves the parallel performance, but also ensures that there is no single point of failure.

LAsynchronous replication

Unlike the RAID storage system, NoSQL replication is usually log-based asynchronous replication. In this way, data can be written to a node as soon as possible without delay caused by network transmission. The disadvantage is that consistency is not always guaranteed. In this way, a small amount of data may be lost when a fault occurs.

L BASE

Compared with the strict ACID feature of transactions, NoSQL databases guarantee the BASE feature. BASE is the final consistency and soft transaction.

1.2 classification of NoSql Databases

Category

Examples example

Typical application scenarios

Data Model

Advantages

Disadvantages

Key-value)

Tokyo Cabinet/Tyrant, Redis, Voldemort, Oracle BDB

Content caching is mainly used to process high access loads of a large amount of data, and also for some log systems.

Key-to-Value pairs, which are usually implemented using hash tables.

Fast search

The data is unstructured and is generally treated as a string or binary data.

Column storage database

Cassandra, HBase, Riak

Distributed File System

Stores data in a column cluster and stores data in the same column.

Fast search speed, high scalability, and easy distributed Expansion

Relatively limited functions

Document Database

CouchDB, MongoDb

Web applications (similar to Key-Value, Value is structured, and the difference is that the database can understand the Value content)

Key-Value pairs corresponding to Key-Value. Value is structured data.

The data structure requirements are not strict, the table structure is variable, and the table structure does not need to be pre-defined like a relational database.

The query performance is not high and there is a lack of unified query syntax.

Graph database

Neo4J, InfoGrid, Infinite Graph

Social networks, recommendation systems, etc. Focus on building relationship Graphs

Graph Structure

Graph structure algorithms are used. Such as Shortest Path addressing and N-degree link Lookup

Most of the time, you need to calculate the entire graph to obtain the required information, and this structure is not good for Distributed cluster solutions.

1.3 MongoDB database features

MongoDB databases have the following features:

L cross-platform, supporting many languages

L free mode

L supports file storage

L easy horizontal scaling

L replica Set Mechanism

L multi-level index

L set-oriented storage

L rich query statements

Based on the above features, MongoDB is suitable for Internet applications with large data volumes, high concurrency, and weak transactions.

2. MongoDB Installation

Here we will mainly introduce the installation on the windows platform (for installation on other platforms, please download the corresponding installation media from the official website ).

2.1 Download and install Media

MongoDB is as follows: https://www.mongodb.org/downloads

Download the corresponding version on windows.

MongoDBVUE (visualization tool): http://www.mongovue.com/downloads/

2.2 Installation

After the download is complete, click Install.

2.2.1 add MongoDB to Environment Variables

The bin directory path of the MongoDB installation directory is as follows: C: \ Program Files \ MongoDB \ Server \ 3.0 \ bin

Add it to the environment variable path. To check whether the mongodb version is successfully added, enter Mongo-version in the command line to view the version number of the installed mongodb. The result is as follows:

2.2.2 start MongoDB

Before starting mongodb, you must specify the corresponding Data (Data storage) directory, log directory, and directory structure, as shown in:

Enter the following command in the command line:

C: \ WINDOWS \ system32> mongod -- dbpath D: \ MangoDB \ Data -- logpath D: \ MangoDB \ Log \ mongodb. log-logappend

This command specifies the data storage directory and log directory for mongodb. Enter the following in the browser:

Http: // localhost: 27017

The following figure shows that the service has been started:

It looks like you are 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. Every time you start the service, you need to enter this line of command, which will be very troublesome. There are two ways to solve this problem:

L save the preceding command as a bat file and click it each time you Start the service (that is, the Start file shown in)

L add MongoDB to the service and start it as a service, as shown below:

Enter the following command in the command line:

C: \ WINDOWS \ system32> mongod -- dbpath D: \ MangoDB \ Data -- logpath D: \ MangoDB \ Log \ mongodb. log -- install -- serviceName "MongoDB"

Enter: net start MongoDB in the command line

The result is as follows:

Input: net stop MongoDB to stop the service.

3. MongoDB Data Model

MongoDB is a document-type database for centralized storage. Its basic concept is different from that of common relational databases.

3.1 documentation

Document is the core concept of MongoDB and is essentially a type of json bjson data.

BSON adds some new data types based on JSON, including date, int32, and int64.

BSON is composed of key-value pairs and has three features: lightweight, traversal, and high efficiency.

3.2 set

Put a set of related documents together to form a set.

A document is equivalent to a piece of information in a relational database, and a set is equivalent to a table in a relational database.

3.3 Database

Multiple documents form a collection and multiple documents form a database. A MongoDB example can host multiple databases, and each database has independent permissions.

3.4 Data Type 3.4.1 Basic Data Type

Null: Null or nonexistent Field

Boolean: true or false

Value Type: Only int32, int64, and double are supported.

String:

Binary data: stores strings of any byte.

Regular Expression: Mainly used for query.

For example: {name:/olive/}, the name field contains olive

{Name:/olive/I}. The name field contains olive and is case insensitive.

{Name:/^ olive/I}. The name field starts with olive and is case insensitive.

Js Code

3.4.2 Date

The date in Mongodb is a 64-bit integer.

The Mongodb storage time is first converted to utc time.

3.4.3 Timestamp

Timestamp is only used internally by mongodb. It is used to record the detailed time of the operation and has no relationship with the date type.

3.4.4 Objectid

Objectid consists of 24 hexadecimal characters. Each byte stores two hexadecimal numbers, which requires 12 bytes of storage space.

3.4.5 embedded documents

As the key value, a document is called an embedded document. Embedded documents do not need to be saved as flat key-value pairs, making the data organization more natural.

Example:

User = {"name": "olive ","Address": {"province": "henan", "city": "zhengzhou "}}

4. MongoDB data update

The example here mainly uses the python language for demonstration.

Introduce the Python driver for MongoDB. First install the pymongo package and enter pip install pymongo in the command line. After the installation is complete, reference it in the code.

Link for creating a database:

#-*-Conding: UTF-8 -*-ImportPymongoImportSysreload (sys) sys. setdefaultencoding ('utf-8') conn = pymongo. consumer Client ('localhost', 27017) db = conn. MDB // create MDB database dt = db. users // create a users data table

After the creation, you can open the created vue to view the created database and data table, as shown in:

4.1 Data insertion 4.1.1 insert

The Insert function can only act on one set. If the set does not exist, the Database Service will automatically create it. If the _ id field is not specified during insertion, this field is automatically added.

#insertuser0 = { '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)

View the inserted data in the specified Vue, as shown in:

In addition, you can also input a list parameter to the insert method, as shown below:

dt.insert([{'name':'Kobe','age':37},{'name':'Jim','age':30}])

View the volume vue again, as shown in (two new data records are added ):

4.1.2 insert_values ()

If you want to insert a large volume of data, you can also use the insert_inserting () method, using the following:

Users = [{'name': 'live' + str (I )}ForIInXrange (101)]
4.2 Data Update

Modify records in a cluster:

Dt. update (filter, update_field, upsert, multi)

Filter: Query condition of update

Update_field: The field to be updated and the update value (similar to set in SQL statements)

Upsert: If no update record exists, true indicates insertion, false indicates no insertion, and the default value is false.

Muti: multiple data records are detected. If true, all data is updated. The default value is false. Only one data record is updated.

Dt. update ({'name': 'live'}, {'$ set': {'age': 100 }})

$ Set: update the specified field value

Usage: {$ set: {field: value }}

$ Unset: delete a specified field

Usage: {$ unset: {field: 1 }}

$ Inc: update the value of a specified field.

Usage: {$ inc: {field: value}

4.3 data deletion

5. MongoDB Data Query 5.1 find () 5.1.1 No parameter by default or find ({}) queries all data.

Find ({},{})

The first {} places the where condition and the second {} specifies the columns to display and not to display (0 indicates not to display 1 indicates to display)

5.1.2 query with Parameters

User = dt. find ({'name': 'live '})

The result is as follows:

5.1.3 query operator use (and query): $ lt, $ lte, $ gt, $ gte, $ ne

User = dt. find ({'name': 'live', 'age': {'$ lt': 90 }})

5.1.4 or query

User = dt. find ({'$ or': [{'name': 'live'}, {'age': {'$ lt': 50}]})

5.1.5 query a field in the embedded document (the. operator is required ):

Insert a document with embedded fields

Dt. insert_one ({'name': '000000', 'address': {'princience ': 'beijinging', 'city': 'beijinging '}})

Example:

User = dt. find ({'address. City': 'beijing '})

5.1.6 in (nin) Query

User = dt. find ({'name': {'$ in': ['live', 'Tom', 'jack']})

User = dt. find ({'name': {'$ nin': ['live', 'Tom ', 'jack']})

5.1.7 sort the query results:

User = dt. find (). sort ('name', pymongo. ASCENDING) // a 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/starting with XXX)

User = dt. find ({"name":/"Olive "/})

5.2 find_one ()

Search for only one piece of information.

Example:

User = dt. find_one ({'name': 'live '})
PrintUser ['name']

The result is as follows:

"Olive"

I wrote an article about how to get started with mongodb, which basically ended here. I hope that my friends who want to get started with mongodb can help me quickly. The examples in this article are all written in python + mongodb. Of course, mongodb officially supports other languages. Here we just want to facilitate the demonstration. If you are interested, you can go to the official mongodb website to check for further research.

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.