Original link http://www.cnblogs.com/zhangzili/p/4975080.html
MongoDB knowledge points at a glance
1. Start the MongoDB database:
Go to the MongoDB installation directory and execute the following command
C:\Program files\mongodb\server\3.0\bin>mongod.exe--dbpath "C:\Program files\mongodb\server\3.0\db"
After successful startup, open a CMD window, enter MongoDB's installation directory, execute Mongo.exe, and enter test library by default.
2. Use database_name is used to create a database. This command will create a new database if the database does not exist, or it will return the existing database.
3, if you want to query the database list, then use the command show DBS; To display the database, you need to insert at least one document in. The default database for MongoDB is test. If no database is created, the collection is saved in the test database.
4. The db.dropdatabase () command is used to delete an existing database.
If you want to delete the new database <mydb>, then the dropdatabase () command will look like this:
|
>use mydbswitched to db mydb >db.dropdatabase ()>{&NBSP; : &NBSP; "MyDB",&NBSP; "OK" : 1} > |
5. Db.createcollection (name, options) is used to create the collection. In the command, name is the names of the collections to create. Options is a document that specifies the configuration of the collection
Options
Field type description
Capped Boolean (optional) If true, it enables the upper bound collection. The upper bound collection is a fixed-size collection that automatically overwrites the oldest entries when it reaches its maximum size. If you specify true, you also need to specify the size of the parameter.
Autoindexid Boolean (optional) If true, the index _id field is created automatically. The default value is False.
Size number (optional) specifies the maximum size of the upper collection byte. If capped is true, you also need to specify this field.
Max Number (optional) specifies the maximum amount of files allowed for the upper bound collection.
There is no need to create collections in MongoDB. When inserting some documents MongoDB will automatically create the collection.
>db.yiibai.insert({"name" : "yiibai"})
>show collections
mycol
mycollection
system.indexes
yiibai
>
6. Delete the db of the collection MongoDB. Collection_name.drop () is used to remove a collection from the database.
The example given below will delete the collection of the given name: mycollection
>use mydb
switched to db mydb
>db.mycollection.drop()
true
>
7. Insert Document: DB. Collection_name.insert (document)
>db.mycol.insert({
_id: ObjectId(7df78ad8902c),
title: ‘MongoDB Overview‘,
description: ‘MongoDB is no sql database‘,
by: ‘yiibai tutorials‘,
url: ‘http://www.yiibai.com‘,
tags: [‘mongodb‘, ‘database‘, ‘NoSQL‘],
likes: 100
})
Here MyCol is our collection name, which was created in the previous tutorial. If the collection does not exist in the database, MongoDB creates this collection and then inserts the document in.
If we do not specify a document that is inserted by the _id parameter, MongoDB assigns a unique objectid to the document.
_ID is a 12-byte hexadecimal number in a collection where each document is unique. 12 bytes are divided as follows:
_id:objectid (4 bytes timestamp, 3 bytes machine ID, 2 bytes process ID, 3 bytes incrementer)
To insert multiple documents in a single query, you can use the array mode of the document insert () command.
Db.mycol.insert ({},{},{},......)
8, query the document: DB. Collection_name.find (), the Find () method will display all the files in an unstructured manner. If the display result is formatted, then you can use the pretty () method.
Grammar
>db.mycol.find().pretty()
In addition to the find () method and the FindOne () method, only one document is returned.
MongoDB's Where Condition:
Operation Syntax example RDBMS equivalent statement
Equality (equals) {<key>:<value>} db.mycol.find ({"By": "Yiibai Tutorials"}). P Retty () Where by = ' Yiibai tutorials '
Less Than {<key>:{$lt: <value>}} db.mycol.find ({"likes": {$lt:)}. Pretty () Where likes < 50
Lesser Than equals (less than equals) {<key>:{$lte: <value>}} db.mycol.find ({"likes": {$lte:]}). Pretty () whe Re likes <= 50
Greater Than (greater than) {<key>:{$gt: <value>}} db.mycol.find ({"likes": {$gt:)}). Pretty () where likes > 50
Greater Than equals (greater than equals) {<key>:{$gte: <value>}} db.mycol.find ({"likes": {$gte:]}). Pretty () where Likes >= 50
Not equals (does not equal) {<key>:{$ne: <value>}} db.mycol.find ({"likes": {$ne:]}). Pretty () where likes! = 50
MongoDB and Conditions:
In the Find () method, if you pass multiple keys through "," to separate them, then MongoDB treats it as if and conditions. The basic syntax is as follows:
>db.mycol.find ({key1:value1, key2:value2}). Pretty ()
MongoDB's OR condition:
To query a file based on an OR condition, you need to use the $or keyword. The basic syntax for or is as follows:
>db.mycol.find({
$or: [
{key1: value1}, {key2:value2}
]
}).pretty()
Example
WHERE clause equivalent to SQL: ' Where likes>10 and (by = ' Yiibai tutorials ' OR title = ' MongoDB Overview ') '
>db.mycol.find ("likes": {$gt: ten}, $or: [{"By": "Yiibai Tutorials"}, {"title": "MongoDB Overview"}]}). Pretty ()
9. Updating and adding documents
The basic syntax for the update () method is as follows
>db. Collection_name.update (Selectioin_criteria, Updated_data)
The following example sets its title "MongoDB Overview" as a new title for the "newly mongodb Tutorial" file.
>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":"Yiibai Tutorial Overview"}
>
By default, MongoDB will only update a single file, update many, and require a parameter ' multi ' set to true.
>db.mycol.update ({' title ': ' MongoDB overview '},{$set: {' title ': ' New MongoDB Tutorial '}},{multi:true})
The Save () method overrides or adds a document: >db. Collection_name.save ({_id:objectid (), new_data})
The following example replaces the file _id ' 5983548781331adf45ec7 '
>db.mycol.save(
{
"_id" : ObjectId(5983548781331adf45ec7), "title":"Yiibai Yiibai New Topic", "by":"Yiibai Yiibai"
}
)
>db.mycol.find()
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"Yiibai Yiibai New Topic", "by":"Yiibai Yiibai"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Yiibai Yiibai Overview"}
>
10. Deleting documents
The Remove () method of MongoDB is used to remove a document from the collection. The Remove () method accepts two parameters. One is the standard missing, the second is the JUSTONE flag
Deletion criteria: Deleting a condition according to the file (optional) will be deleted.
Justone: (optional) If set to TRUE or 1, then remove only one document.
The following example will delete all files with the title ' MongoDB Overview '
>db.mycol.remove ({' title ': ' MongoDB Overview '})
If there are multiple records, and you want to delete only the first record, then set the parameter Justone in the Remove () method.
>db. Collection_name.remove (deletion_criteria,1)
If you do not specify a delete condition, MongoDB deletes the entire file from the collection. This is equivalent to the SQL TRUNCATE command.
>db.mycol.remove ({}) >db.mycol.find () >
11. Find () part field (MongoDB projection)
The MongoDB projection meaning is to select only the data you want, not the entire document. If a document has 5 fields, you only need to display 3, and only select 3 fields from it.
MongoDB's Find () method, which explains the second optional parameter in MongoDB that the query document receives is the list of fields to retrieve. In MongoDB, when the Find () method is executed, it displays all the fields of a document. To limit this, you need to set the field list value to 1 or 0. 1 is used to display the field, while 0 is used to hide the field.
Grammar
The basic syntax for the Find () method is as follows
>db. Collection_name.find ({},{key:1})
12. The Limit () method shows how many rows
To restrict logging in MongoDB, you need to use the limit () method. The limit () method accepts a numeric type parameter, which is the number of documents to display.
Grammar
The basic syntax for the limit () method is as follows
>db. Collection_name.find (). Limit (number)
There is also a method skip () also accepts numeric type parameters and is used to skip the number of files.
Grammar
The basic syntax for the Skip () method is as follows:
>db. Collection_name.find (). Limit (number). Skip (number)
Example:
The following example shows only the second document.
Starting from the second line, check only one:
>db.mycol.find ({},{"title": 1,_id:0}). Limit (1). Skip (1) {"title": "NoSQL Overview"}>
Please note that the default value for the Skip () method is 0
13. Sort the document (sort the queried data)
To sort the documents in MongoDB, you need to use the sort () method. The sort () method accepts a document that contains a list of fields and a sort order. To specify the sort order using 1 and 1. 1 is used for ascending, while-1 is for descending.
Grammar
The basic syntax for the sort () method is as follows
>db. Collection_name.find (). Sort ({key:1})
The following example sorts the displayed file sort by title in descending order.
>db.mycol.find({},{"title":1,_id:0}).sort({"title":-1})
{"title":"Yiibai Yiibai Overview"}
{"title":"NoSQL Overview"}
{"title":"MongoDB Overview"}
>
Note that if you do not specify a sort type, the sort () method arranges the document in ascending order.
14. MongoDB Index
Indexes support queries for efficient execution. Without an index, MONGODB must scan every document in the collection, and then select the documents that match the query statement. Scanning is very inefficient if mongod is needed to process large amounts of data.
Indexes are special data structures that are stored in a small fraction of the data that is easy to set up in traversal form. The index stores the values in the index that specify a specific field, or a set of fields, and sorts the values of the fields.
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})
Here the key is to create an indexed field, and 1 is sorted by name in ascending order. If you are creating an index in descending order, you need to use-1.
Example:
>db.mycol.ensureindex ({"title": 1}) >
In the Ensureindex () method, multiple field indexes can be created through multiple fields.
>db.mycol.ensureindex ({"title": 1, "description":-1})
The Ensureindex () method also accepts a list of options (which is optional), with the following list:
Parameter type description
Background Boolean Build index in the background so that indexing does not block other database activity. Specifies true when established in the background. The default value is False.
The unique Boolean creates a unique index so that the collection will not accept the inserted document, where the index keyword or key matches the existing value of the index. Specify true to create a unique index. The default value is False.
Name of the string index. If not specified, MongoDB generates an index name by the name of the field and sort order of the connection index.
Dropdups Boolean may have duplicates when creating a unique index of a field. The MongoDB index key appears only for the first time and removes all documents from the collection that contain subsequent occurrences of the key. Specify true to create a unique index. The default value is False.
Sparse Boolean If True, the index references only the document with the specified field. These indexes use less space, but in some cases behave differently (especially sort). The default value is False.
Expireafterseconds integer Specifies the value, in seconds, as a TTL control for how long MongoDB retains this collection file.
The version number of V index version. The default index version depends on the version that is run when the index is mongod created.
Weights document Weight (weight) is a number, which is a number from 1 to 99,999, indicating the significance of the field in terms of the score relative to other indexed fields.
Default_language string for the text index, and for the language in the Stemmers and tag generator lists, determines the deactivation words and rules. Its default value: 中文版.
Language_override string for a text index that contains the name of the specified field in the document, and the language to override the default language. Its default value: Language.
15. MongoDB Aggregation
The aggregation operation processes the data record and returns the result of the calculation. Aggregating grouping operations values from multiple documents, and can perform multiple operations on grouped data to return a result. COUNT (*) in SQL, using group by with MongoDB aggregation is equivalent. For MongoDB aggregation, the aggregate () method is used.
Grammar
The basic syntax for the aggregate () method is as follows
>db. Collection_name.aggregate (aggregate_operation)
Example:
The following data is available in the collection:
|
{_id: ObjectId(7df78ad8902c)title: ‘MongoDB Overview‘,description: ‘MongoDB is no sql database‘,by_user: ‘Yiibai Yiibai ‘,url: ‘http://www.yiibai.com‘,tags: [‘mongodb‘, ‘database‘, ‘NoSQL‘],likes: 100},{_id: ObjectId(7df78ad8902d)title: ‘NoSQL Overview‘,description: ‘No sql database is very fast‘,by_user: ‘Yiibai Yiibai‘,url: ‘http://www.yiibai.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} |
Now from the collection above, if you want to know how many tutorials each user has written, then use the aggregate () method, as shown in the list:
> db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : 1}}}])
{
"result" : [
{
"_id" : "Yiibai Yiibai",
"num_tutorial" : 2
},
{
"_id" : "Neo4j",
"num_tutorial" : 1
}
],
"ok" : 1
}
>
Used for the above purposes will be equivalent to SQL query: Select By_user, COUNT (*) from MyCol GROUP by By_user
Also, in the above example, we have used the field By_user to group and calculate the sum, that is, by_user the number of occurrences. A clustered expression that is available in a list.
Expression Description Example
$sum Db.mycol.aggregate ([{$group: {_id: "$by _user", num_tutorial: {$sum: "$likes"}} from the collection to accumulate all the defined values in the document. }])
$avg calculates the average of all given values from all documents in the collection db.mycol.aggregate ([{$group: {_id: "$by _user", num_tutorial: {$avg: "$likes"}} }])
$min the smallest corresponding value for all files obtained from the collection db.mycol.aggregate ([{$group: {_id: "$by _user", num_tutorial: {$min: "$lik Es "}}}])
$max gets the maximum value from the corresponding value in all documents in the collection db.mycol.aggregate ([{$group: {_id: "$by _user", num_tutorial: {$max: "$likes"}} }])
$push inserting an array value into the document Db.mycol.aggregate ([{$group: {_id: "$by _user", url: {$push: "$url"}}])
$addToSet Insert a value from the resulting array into the document, but does not produce duplicate db.mycol.aggregate ([{$group: {_id: "$by _user", url: {$addToSet: "$url"}}} ])
$first gets the header file according to the grouping from the source file. Usually, this makes it only possible to add some previously applied "$sort"-stage db.mycol.aggregate ([{$group: {_id: "$by _user", First_url: {$first: "$url"}}])
$last gets the last file from the source file according to the grouping. Typically, this makes it only possible to add some of the previously applied "$sort"-stage. Db.mycol.aggregate ([{$group: {_id: "$by _user", Last_url: {$last: "$url"}}])
16. MongoDB Create Backup
To use the Mongodump command to perform a MongoDB database backup. This command dumps all data from the server to the dump directory. There are many options available through which you can limit the amount of data or create remote server backups.
Grammar
The basic syntax for the Mongodump command is as follows
>mongodump
Example
Start the Mongod server. Assume that the Mongod server is running on a local host and Port 27017. Now open a command prompt, then go to the bin directory of your MongoDB instance and enter the command mongodump.
Consider the MyCol collection with the following data.
>mongodump
The command connects to server 127.0.0.1 and Port 27017, and backs up all data to the directory on the server:/bin/dump/.
The above is a list of available options that can be used with the Mongodump command.
This command will only back up the specified database to the specified path
Syntax Description Example
Mongodump--host host_name--port port_number This command backs up all databases for the specified Mongod instance mongodump--host yiibai.com--port 27017
Mongodump--dbpath db_path--out backup_directory mongodump--dbpath/data/db/--out/data/backup/
Mongodump--collection Collection--db db_name This command backs up only the specific set of databases specified Mongodump--collection mycol--db test
17. Data Recovery
To restore the backed up MongoDB data, use the Mongorestore command. This command restores all data from the backup directory.
Grammar
Basic syntax for the Mongorestore command
>mongorestore
"Turn" MongoDB knowledge points at a glance