MongoDB installation, configuration and detailed tutorial

Environment: win10   

Download: https: //pan.baidu.com/s/1a0SwRv9er3HTewzcI8nWgQ     

Extraction code: dyyx  

Once downloaded, the file folder in the root directory of the C drive, and then to configure the system environment variables, add in the PATH C: \ mongodb \ bin, and then click OK

This folder, there are two .bat file ending, one startservice.bat (server), one startclient.bat (clients), we opened, first open the first (server), and then open the second (client), then in a second operation (client) inside.

 

Instructions:

1, MongoDB help ------- db.help ()

2, Mongodb statistics ------ db.stats ()

Just installed on MongoDB, the default default database to test, create a collection of this time, the test will be saved in the database

3. Create a database ------ use + databaseNmae, such as: use mydb

4, check the database currently resides ------ db

5, view the database list ------ show dbs

 

6, delete the database ------ db.dropDatabase ()

First, go to the database to be removed, use databaseName, after db.dropDatabase (), in the view show dbs, this time found, has been successfully removed 

7, create a collection ------ db.createCollection (name, options)

① without parameters, view the collection ------ show collections

② arguments

In MongoDB, you do not need to create a collection. When you insert some documents, MongoDB will automatically create a collection.

8, delete a collection ------ db.collectionName.drop ()

MongoDB use db.collectionName.drop()to remove the collection database.

If successful, delete the selected collections, the drop()method returns true, otherwise false.

9, data types

MongoDB supports the following data types:

  • String: string. Storing data commonly used data types. In MongoDB, UTF-8 encoded string is legal.
  • Integer: integer value. It is used to store values. The server you are employed, can be divided into 32-bit or 64-bit.
  • Boolean: Boolean value. For storing Boolean values ​​(true / false).
  • Double: double precision floating point value. Used to store floating-point values.
  • Min / Max keys: the minimum value of a value BSON (binary JSON) element of the highest value and the relative ratio.
  • Arrays: for the array or list one or more values ​​are stored as a key.
  • Timestamp: timestamp. Modify or add records document a specific time.
  • Object: for the embedded documents.
  • Null: Creates an empty value.
  • Symbol: Symbol. Substantially equivalent to the data type string type, but the difference is that it uses special symbols generally used type of language.
  • Date: Date Time. UNIX time format used to store the current date or time. You can specify your own date and time: Date of creation
    as incoming date information.
  • Object ID: object ID. ID used to create the document.
  • Binary Data: binary data. For storing binary data.
  • Code: Code Type. JavaScript code is used to store the document.
  • Regular expression: regular expression type. It used to store regular expressions.

10, into the document ------ db.collectionNmae.insert (document)

To insert data into MongoDB collection, use insert(), or save()method.
insert()Or save()the difference method d when the main key is repeated, insert()being given, save()overwrites the previous contents.

Example 1

mycol is the name of a collection that is created. If the set does not exist in the database, then MongoDB creates the collection, and insert the document.
The insertion of the document, if we do not specify _id argument, then MongoDB automatically assigns a unique ID for the document.
For, you can () method passing a document with an array of insert, as shown here:

Example 2

> 传入多条数据 格式:db.mycol.insert([{},{},{}])
>db.post.insert([
{
title: 'MongoDB Overview',
description: 'MongoDB is no sql database',
by: 'tutorials point',
url: 'http://www.tutorialspoint.com',
tags: ['mongodb', 'database', 'NoSQL'], likes: 100 }, { title: 'NoSQL Database', description: 'NoSQL database doesn't have tables', by: 'tutorials point', url: 'http://www.tutorialspoint.com', tags: ['mongodb', 'database', 'NoSQL'], likes: 20, comments: [ { user:'user1', message: 'My first comment', dateCreated: new Date(2013,11,10,2,35), like: 0 } ] } ]) 

It can also be used db.post.save(document)to insert the document. If no document _id, so save()on and insert()completely different. If the _id document specified, it will overwrite all the data contained save () method of the document _id specified.

11, query document ------ db.collectionName.find ()

find()The method will be an unstructured way to display all documents.
pretty()A method to display the result of format, using the pretty()method.
Syntax
>db.COLLECTION_NAME.find().pretty()

example

 
 

In addition to find () method, there are a findOne () method simply returns a document.

12, MongoDB similar to the WHERE clause of the statement

If you want to find documents based on a number of conditions, you can use the following operations.

operating format example RDBMS Similar statements
equal {<key>:<value> } db.mycol.find({"by":"tutorials point"}).pretty() where by = 'tutorials point'
Less than {<key>:{$lt:<value>}} db.mycol.find({"likes":{$lt:50}}).pretty() where likes < 50
less than or equal to {<key>:{$lte:<value>}} db.mycol.find({"likes":{$lte:50}}).pretty() where likes <= 50
more than the {<key>:{$gt:<value>}} db.mycol.find({"likes":{$gt:50}}).pretty() where likes > 50
greater than or equal to {<key>:{$gte:<value>}} db.mycol.find({"likes":{$gte:50}}).pretty() where likes >= 50
not equal to {<key>:{$ne:<value>}} db.mycol.find({"likes":{$ne:50}}).pretty() where likes != 50

13, MongoDB And the conditions

Syntax

In the find()process, if the incoming plurality of keys, and (,) are separated by a comma, then it will be seen as MongoDB AND condition. The basic syntax AND conditions are as follows:
db.mycol.find({key1:value1, key2:value2}).pretty()

example

The following example will show all the "tutorials point" published entitled "MongoDB Overview" tutorial.

For the example case, RDBMS will be used in the WHERE clause: where by='tutorials point' AND title='MongoDB Overview'. You can pass any clause in the find pairs.

14, MongoDB the OR condition

If the query document based on OR conditions, you can use keywords $or. The basic syntax for OR conditions:

15, used in conjunction with AND OR condition

example

The following example shows the condition of the document is: love is greater than the number 100, entitled "MongoDB Overview", or by "tutorials point" published. SQL WHERE clause for the response:where likes>10 AND (by = 'tutorials point' OR title = 'MongoDB Overview')

> 格式:db.mycol.find({},$or:[{},{}])

16, updated documentation

MongoDB in the update () and save () method can be used to update the collection of documents. update () method to update the value of an existing document, and save () method is a method of using the incoming document to replace the existing document.

① update () method ------ update the values ​​that already exist in the document

Syntax

update()The basic method of the following format:
db.COLLECTION_NAME.update(SELECTIOIN_CRITERIA, UPDATED_DATA)

example

If you set mycol following data:

{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"} { "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"} 

The following example will document the original title 'MongoDB Overview' is replaced with the new title 'New MongoDB Tutorial'.

>db.mycol.update({'title':'MongoDB Overview'},{$set:{'title':'New MongoDB Tutorial'}}) >db.mycol.find() { "_id" : ObjectId(5983548781331adf45ec5), "title":"New MongoDB Tutorial"} { "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"} { "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"} 

MongoDB default update only a single document, in order to update multiple documents need to be multi parameter set to true.

>db.mycol.update({'title':'MongoDB Overview'},{$set:{'title':'New MongoDB Tutorial'}},{multi:true}) 

② save () method

save()Method to replace the existing document passed to the method of use of the document.
Syntax
save()Method basic syntax is as follows:
db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})

example

The following example is to update the document _id '5983548781331adf45ec7' of.

>db.mycol.save(
{
"_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point New Topic", "by":"Tutorials Point" } ) >db.mycol.find() { "_id" : ObjectId(5983548781331adf45ec5), "title":"New MongoDB Tutorial"} { "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"} { "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point New Topic", "by":"Tutorials Point"} 

17, delete the document ------ db.collectionName.remove ()

MongoDB using the remove()method of removing the collection of documents. It has two optional parameters:

  • deletion criteria :( optional) delete the standard document.
  • justOne :( Optional) If true or 1, only delete a document.

Syntax

remove()The basic syntax of the method is as follows:
db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)

example

If mycol set contains the following data:

{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"} { "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"} 

Below we will delete all titled 'MongoDB Overview' document.

>db.mycol.remove({'title':'MongoDB Overview'})
>db.mycol.find()
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"} { "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"} 

18, only delete a document

If there are multiple records, and you want to delete the first record, then set the remove () justOne parametric methods:
db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)

19, delete all documents

If no deletion criteria, then MongoDB collection of all documents will be deleted. This is equivalent to truncate the SQL command.

>db.mycol.remove()
>db.mycol.find() 

20, the mapping

In MongoDB, the mapping (Projection) refers to the need to select only the data in the document, rather than all data. If the document has five fields, and you only need to show three, then simply select the field to three.

21, find () method

MongoDB query document has been introduced find()method, either use AND or OR conditions to obtain a list of all the fields you want to display all the fields in a document. To limit may be set to 1 or 0 using a field list. 1 for displaying a field 0 is used for hidden fields.

Syntax

The basic syntax mapping with find () method is:
db.COLLECTION_NAME.find({},{KEY:1})

example

If mycol collection have the following data:

{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"} { "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"} 

The following example will show the document title in the query document.

>db.mycol.find({},{"title":1,"_id":0})
{"title":"MongoDB Overview"}
{"title":"NoSQL Overview"} {"title":"Tutorials Point Overview"} 

Note: When you execute find () method, _id field is always on display. If you do not want to display the field, you can set it to 0.

22, the recording limit ------ limit () and Skip ()

① limit () method

To limit the records in MongoDB, you can use limit()the method. limit()The method accepts a value type parameter, a value of the number of documents desired to be displayed.

Syntax

limit()The basic method syntax is:
db.COLLECTION_NAME.find().limit(NUMBER)

example

Mycol set of assumptions have the following data:

{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"} { "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"} 

The following example will show only two documents in the query document.

>db.mycol.find({},{"title":1,_id:0}).limit(2)
{"title":"MongoDB Overview"}
{"title":"NoSQL Overview"} 

If no limit()numeric parameter method, all documents in the set is displayed.

② skip () method

Syntax

skip()The basic method syntax is:
db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)

example

The following example will show only the second document:

>db.mycol.find({},{"title":1,_id:0}).limit(1).skip(1)
{"title":"NoSQL Overview"}

Note: skip()The default value is 0 in the method.

23, record sorting

① sort () method

MongoDB is a document ordering through sort()methods to achieve. sort()The method may be specified by a number of parameter fields to be sorted, using a specified ordering and -1, where 1 denotes ascending, descending and -1 means.

Syntax

sort() Methods The basic format is:
db.COLLECTION_NAME.find().sort({KEY:1})

example

Myycol hypothesis set contains the following data:

{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"} { "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"} 

The following example will display the title of the document are arranged in descending order.

>db.mycol.find({},{"title":1,_id:0}).sort({"title":-1}) {"title":"Tutorials Point Overview"} {"title":"NoSQL Overview"} {"title":"MongoDB Overview"} 

Note that, if the collation is not specified, Sort () method to display the document in ascending order.

24, Index

Index enables efficient query. There is no index, MongoDB must scan all the documents in the collection, to find documents matching a query. This scan inefficient at all, we need to process large amounts of data.
Index is a special data structure, a small data set is saved as a form readily traverse. Capable of storing an index value of a particular field or set of fields, and in the manner specified by index sorted field values.

① ensureIndex () method

To create an index, you need to use MongoDB's ensureIndex () method.

Syntax

ensureIndex()The basic method syntax is:
db.COLLECTION_NAME.ensureIndex({KEY:1})
Key here is to create the field name of the index, a representative arranging field values in ascending order. -1 is sorted in descending order.

example

>db.mycol.ensureIndex({"title":1})

It can be ensureIndex()passed in a number of fields method to create multiple index fields.

>db.mycol.ensureIndex({"title":1,"description":-1}) 

ensureIndex() The method can also accept a number of optional parameters, as follows:

parameter Types of description
background Boolean value Construction of the index in the background, so as not to interfere with other activities in the database. When the value is true, on behalf of indexing in the background. The default value is false
unique Boolean value Create a unique index, so that when the key index when the index matched a value already exists, do not accept the insertion of a collection of documents. Create a unique index value to true representative. The default value is false.
name String Index name. If not specified, MongoDB binds sorting index field name and serial number, to generate an index name.
dropDups Boolean value Create a unique index may be repeated in the field. ongoDB only when a key index for the first time, remove all the documents at the time of the follow-up key appears.
sparse Boolean value If true, the index reference only documents with the specified field. These indexes occupy less space, but the performance in some cases are also different (especially the sort). The default value is false.
expireAfterSeconds Integer value One second specified value, as the holding time TTL controls MongoDB documents in the collection.
v Index version Index version number. The default version of the index with MongoDB version running when creating an index.
weights File 数值,范围从 1 到 99, 999。表示就字段相对于其他索引字段的重要性。
default_language 字符串 对文本索引而言,用于确定停止词列表,以及词干分析器(stemmer)与断词器(tokenizer)的规则。默认值为 english。
language_override 字符串 对文本索引而言,指定了文档所包含的字段名,该语言将覆盖默认语言。默认值为 language。

25、聚合

聚合操作能够处理数据记录并返回计算结果。聚合操作能将多个文档中的值组合起来,对成组数据执行各种操作,返回单一的结果。它相当于 SQL 中的 count(*) 组合 group by。

① aggregate() 方法

对于 MongoDB 中的聚合操作,应该使用 aggregate()方法。

语法格式

aggregate() 方法中的基本格式如下所示:
db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)

范例

假如某个集合包含下列数据:

{
_id: ObjectId(7df78ad8902c)
title: 'MongoDB Overview',
description: 'MongoDB is no sql database',
by_user: 'tutorials point', url: 'http://www.tutorialspoint.com', tags: ['mongodb', 'database', 'NoSQL'], likes: 100 }, { _id: ObjectId(7df78ad8902d) title: 'NoSQL Overview', description: 'No sql database is very fast', by_user: 'tutorials point', url: 'http://www.tutorialspoint.com', tags: ['mongodb', 'database', 'NoSQL'], likes: 10 }, { _id: ObjectId(7df78ad8902e) title: 'Neo4j Overview', description: 'Neo4j is no sql database', by_user: 'Neo4j', url: 'http://www.neo4j.com', tags: ['neo4j', 'database', 'NoSQL'], likes: 750 } 

假如想从上述集合中,归纳出一个列表,以显示每个用户写的教程数量,需要像下面这样使用 aggregate() 方法:

> db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : 1}}}])
{
"result" : [ { "_id" : "tutorials point", "num_tutorial" : 2 }, { "_id" : "Neo4j", "num_tutorial" : 1 } ], "ok" : 1 } 

假如用 SQL 来处理上述查询,则需要使用这样的命令:select by_user, count(*) from mycol group by by_user
上例使用 by_user 字段来组合文档,每遇到一次 by_user,就递增之前的合计值。下面是聚合表达式列表。

表达式 描述 范例
$sum 对集合中所有文档的定义值进行加和操作 db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : "$likes"}}}])
$avg 对集合中所有文档的定义值进行平均值 db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$avg : "$likes"}}}])
$min 计算集合中所有文档的对应值中的最小值 db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$min : "$likes"}}}])
$max 计算集合中所有文档的对应值中的最大值 db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$max : "$likes"}}}])
$push 将值插入到一个结果文档的数组中 db.mycol.aggregate([{$group : {_id : "$by_user", url : {$push: "$url"}}}])
$addToSet 将值插入到一个结果文档的数组中,但不进行复制 db.mycol.aggregate([{$group : {_id : "$by_user", url : {$addToSet : "$url"}}}])
$first 根据成组方式,从源文档中获取第一个文档。但只有对之前应用过 $sort 管道操作符的结果才有意义。 db.mycol.aggregate([{$group : {_id : "$by_user", first_url : {$first : "$url"}}}])
$last 根据成组方式,从源文档中获取最后一个文档。但只有对之前进行过 $sort 管道操作符的结果才有意义。 db.mycol.aggregate([{$group : {_id : "$by_user", last_url : {$last : "$url"}}}])

管道的概念

在 UNIX 命令 Shell 中,管道(pipeline)概念指的是能够在一些输入上执行一个操作,然后将输出结果用作下一个命令的输入。MongoDB 的聚合架构也支持这种概念。管道中有很多阶段(stage),在每一阶段中,管道操作符都会将一组文档作为输入,产生一个结果文档(或者管道终点所得到的最终 JSON 格式的文档),然后再将其用在下一阶段。
聚合架构中可能采取的管道操作符有:

  • $project 用来选取集合中一些特定字段。
  • $match 过滤操作。减少用作下一阶段输入的文档的数量。
  • $group 如上所述,执行真正的聚合操作。
  • $sort 对文档进行排序。
  • $skip 在一组文档中,跳过指定数量的文档。
  • $limit 将查看文档的数目限制为从当前位置处开始的指定数目。
  • $unwind 解开使用数组的文档。当使用数组时,数据处于预连接状态,通过该操作,数据重新回归为各个单独的文档的状态。利用该阶段性操作可增加下一阶段性操作的文档数量。

26、创建备份

数据库备份

为了在 MongoDB 中创建数据库备份,需要使用 mongodump 命令。该命令会将服务器上的所有数据都转储到 dump 目录中。你可以使用很多选项来限制转储的数据量,或者创建远程服务器备份。

语法格式

mongodump 命令的基本语法格式为:
mongodump

范例

开启 mongod 服务器。假设 mongod 服务器运行在 localhost 上,端口为 27017。在命令行上输入命令,在 MongoDB 实例的 bin 目录下输入 mongodump 命令。
假设 mycol 集合包含如下数据:
>mongodump
上述命令会连接在 127.0.0.1 运行的服务器(端口为 27017),将所有数据备份到 /bin/dump 上。命令输出结果如下图所示:

 
创建备份

mongodump 命令其实包含很多选项。

语法格式 描述 范例
mongodump --host HOST_NAME --port PORT_NUMBER 该命令将指定 mongod 实例上的所有数据库都进行了备份 mongodump --host tutorialspoint.com --port 27017
mongodump --dbpath DB_PATH --out BACKUP_DIRECTORY 该命令将指定数据库内容存放目录和备份输出目录 mongodump --dbpath /data/db/ --out /data/backup/
mongodump --collection COLLECTION --db DB_NAME 该命令只备份那些指定路径上的指定数据库 mongodump --collection mycol --db test

27、恢复备份

重新恢复数据

恢复备份数据使用 mongorestore 命令,该命令将备份目录中的所有数据给予恢复。

语法格式

mongorestore 命令的基本语法格式为:
> mongorestore

范例

该命令输入结果如下图所示:

 

Guess you like

Origin www.cnblogs.com/taotao0805/p/11401473.html