MongoDB 第1-3 Chapter Add, modify, modifier notes:
Note: As with MySQL queries, always think about optimizing the time and performance of querying data
Db.help ()//Database Help information
Db.blog.help ()//Collection Help information
Db.c.find (). Help ()//Return child method information for the find () method
Emptying collection data
Db.blog.remove ()
Inserting information
Db.blog.insert ({' title ': ' bbbbb ', ' content ': ' BFBFBF ', ' Hits ': 1})
$inc is modifier, can only be used for integers, long shaped, floating-point type
Db.blog.update ({' title ': ' AAAAA '}, {' $inc ': {' hits ': 1}})
$set is a modifier for $inc and string modification
Db.blog.update ({' title ': ' AAAAA '}, {' $set ': {' content ': ' Testcontent '}})
Simple new attributes/each time the overlay is more troublesome
AA = Db.blog.findOne ({' title ': ' AAAAA '})
Aa.arr = [' View ', ' click ']
Db.blog.update ({' title ': ' AAAAA '}, AA)
If comments exists $push will insert data at the end of the data, anyway create comments $push can only operate
Db.blog.update ({' title ': ' AAAAA '}, {' $push ': {' comments ': {' name ': ' Zhang San ', ' content ': ' My flash ', ' Reply ': 0}}})
$addToSet is the same as the $push type, except that you can avoid inserting duplicates
Db.blog.update ({' title ': ' AAAAA '}, {' $addToSet ': {' comment ': {' name ': ' Zhang San ', ' content ': ' My flash ', ' Reply ': 0}}})
Delete Comment Node properties
Db.blog.update ({' title ': ' AAAAA '}, {' $unset ': {' comments ': {}}})
$pull Delete the one-dimensional array option for the view data
Db.blog.update ({' title ': ' AAAAA '}, {' $pull ': {' arr ': ' View '}})
The positioning modifier of an array, one of two ways is position, and one is the positioning operator (' $ ')
Db.blog.update ({' title ': ' AAAAA '}, {' $inc ': {' comments.0.reply ': 1}})
Only the value of the first array element is modified here
Db.blog.update ({' comments.name ': ' Zhang San '}, {' $set ': {' comments.$.content ': ' TESTTEMTNSD '}})
Query Document Number
Db.blog.count ({' title ': ' AAAAA '})
Db.blog.find ({' title ': ' AAAAA '}). Count ()
Update multiple documents, by default only the first document that meets the criteria is updated, and if you want to update multiple documents, you need to set the fourth parameter of update to True
Db.blog.update ({' title ': ' AAAAA '}, {' $inc ': {' hits ': 1}}, False, True)
n indicates the number of documents updated, Updatedexisting=true indicates that the document has been updated
Db.runcommand ({' GetLastError ': 1})
Remove the last element of comments {' $pop ': {key:1}} end remove/{' $pop ': {key:-1}} first remove
Db.blog.update ({"_id": ObjectId ("53fdb010fb4b2154fd546233")},{' $pop ': {' comments ': 1}})
Db.blog.find ()
MongoDB the fourth chapter inquires the note:
Simple query
Db.blog.find ()//query collection all document data should be 20 by default, and find () is equivalent to find ({})
Db.blog.findOne ()//query collection one document data, FindOne () equivalent to FindOne ({})
Parallel condition query "and"
Db.blog.find ({' title ': ' AAAAA ', ' Hits ': 10})
Query for the specified number of columns "SELECT" NOTE: _id specifies also returned
Db.blog.find ({' title ': ' AAAAA '}, {' title ': 1, ' Hits ': 1})
Exclude a method that does not display the specified field or does not display the _id method
Db.blog.find ({' title ': ' AAAAA '}, {' comments ': 0, ' _id ': 0})
Query criteria ' < ', ' <= ', ' > ', ' >= ', ' <> ' correspond to ' $lt ', ' $lte ', ' $gt ', ' $gte ', ' $ne ', ' $ne ' adapted to all types
Db.blog.find ({' hits ': {' $lt ': +, ' $gt ': 1}})
Db.blog.find ({' hits ': {' $lte ': +, ' $gte ': 1}})
Db.blog.find ({' title ': {' $ne ': ' Dfdfdf '}})
$or $in Query notes: The first condition can query more information as much as possible so as to improve efficiency
Db.blog.find ({' $or ': [{' title ': ' AAAAA '}, {' Hits ': 1}]})
Db.blog.find ({' title ': {' $in ': [' aaaaa ', ' VVVVV '}})
Db.blog.find ({' $or ': [{' title ': {' $in ': [' aaaaa ', ' BBBBB '}}}, {' Hits ': 1}]})
Take the operation symbol $mod NOTE: $mod will be the first value of the query in addition to $mod the first given value, if the remainder is equal to the second $mod the given value returns the result
Db.blog.find ({' hits ': {' $mod ': [2, 1]}})//Note will return hits to 1 3 5 7 9 .....
$not documents that are used to query for a specified condition that are not compliant are usually used with the regular
Db.blog.find ({' hits ': {' $not ': {' $mod ': [2, 1]}}})//Note will return hits to 2 4 6 8 10 .....
The query key value is NULL, and null matches the document data where the key value is null and the key value does not exist
Db.blog.find ({' Nokey ': null})
You want to query a document with a key value of NULL but you want to exclude a document method that does not exist for a key value using $exists and $in
Db.blog.find ({' Test ': {' $in ': [null], ' $exists ': true}})
Array of queries
Db.blog.insert ({' Fruit ': [' apple ', ' banana ']})
Db.blog.insert ({' Fruit ': [' apple ', ' Putao ']})
Db.blog.insert ({' Fruit ': [' chengzi ', ' Banana ']})
Db.blog.find ({' Fruit ': ' apple ', ' fruit ': ' banana ')//Note this is not a reasonable formulation.
The above array query is problematic, inaccurate, and requires the use of $all
Db.blog.find ({' Fruit ': ' apple '})
Db.blog.find ({' Fruit ': ' banana '})
Query the document array with ' apple ' and ' banana ' data results to get a record
Db.blog.find ({' fruit ': {' $all ': [' apple ', ' Banana '}})
If you only want to query the array the second element is ' banana ' result using an array subscript
Db.blog.find ({' Fruit.1 ': ' Banana '})
You can use $push and $addtoset to home arrays
Db.blog.update ({"_id": ObjectId ("53fec26ab5e462a952616f0a")}, {' $addToSet ': {' fruit ': ' Liulian '}})
To return the first 3 messages of an array of documents $slice the second parameter of the Find function is the column of the query (select)
Db.blog.find ({' title ': ' AAAAA '}, {' comments ': {' $slice ': 3}})
Want to return the second to 4th message of the document array $slice
Db.blog.find ({' title ': ' AAAAA '}, {' comments ': {' $slice ': [1, 3]}})
Gets the last piece of information in the document array
Db.blog.find ({' title ': ' AAAAA '}, {' comments ': {' $slice ':-1}})
Querying inline document queries is related to the order of key values so the following two ways should be the first way, the second way is to write a full subset of keys
Inline document matching requires an exact match to the entire document
Db.blog.find ({' title ': ' AAAAA ', ' comments.name ': ' 111 '})
Db.blog.find ({' comments ': {' name ': ' 111 '}})
$where query Other query methods can not be implemented when you need to use the $where query
Not to be able to use $where he's slower than other query performance.
Db.blog.insert ({' X ': 5, ' Y ': 5})
Db.blog.insert ({' X ': 3, ' Y ': 7})
Db.blog.insert ({' X ': 4, ' Y ': 6})
Db.blog.insert ({' X ': 1, ' Y ': 8})
Db.blog.find ({' $where ': ' this.x + this.y = = 10 '})
Db.blog.find ({' $where ': ' function () {return this.x + This.y = = 10;} '})
Cursor
/*
Db.c.remove ()
for (I=1; i<100; i++) {
Db.c.insert ({' X ': i})
}*/
Db.c.count ()
Document data for a cursor loop query
/*
var data = Db.c.find ()
while (Data.hasnext ()) {
obj = Data.next ()
Print (obj.x)
}*/
Or you can use the foreach
var data = Db.c.find ()
Data.foreach (function (d) {print (d.x)})
Returns a certain number of results sorted with sort skip limit
Note: Three sequences can be paired but usually in the order above
{x:1} x key value Ascending, {x: -1}x key value Descending if you specify multiple keys to sort by key
Db.c.find (). Sort ({' X ': 1}). "Limit (10)////By X-key value in ascending order and fetch 10 records from the 10th start
Db.c.find (). Sort ({' X ': 1}). Limit (10)//By default fetch 10 data from the first bar
Db.c.find (). Sort ({' X ': 1}). Skip (10)//start with all data from 10th
Comparison order
Sometimes a key value can have more than one type, and MongoDB handles different types of data in a sequential order:
Minimum value
Null
Digital (integer, long, double)
String
Objects/Documents
Array
Binary data
Object ID
Boolean type
Date type
Time stamp
Regular expressions
Maximum Value
Note: Avoid skipping over a lot of results with skip it's a pit, dad.
Randomly select a document
Picking a document randomly from a collection is a common problem, and the stupidest way to do this is to select the total number of rows in the query collection and then take the random number between 0 and the total number of rows.
At this point, Db.blog.find (). Skip (xxxx). Limit (1) skip may be slightly too large to affect query performance
Note: I recommend adding a field when inserting a document size integer, equivalent to the self-increment ID of the relational database, can take out the last ID of a 100th record,
And then compare it with the ID
You can use the Math.random () class to randomly query
var total = Db.c.find (). Count ()
var random = Math.floor (Math.random () *total)
Db.c.find (). Sort ({' X ': 1}). Skip (Random). Limit (1)
MongoDB Chapter Fifth Index notes:
Indexes are used to speed up queries.
Create an index to use the Ensureindex () method, the same set contract one index only needs to be created once, multiple creation is futile
Indexes are directional, individual indexes do not need to take direction but multiple indexes need to take direction
Db.c.ensureindex ({' X ': 1})//create ascending index {x:1}, {x:-1}
The direction of the index such as {' user_name ': 1, ' age ':-1} The result will be sorted in ascending order of ' user_name ', with the same username in descending order of ' age '
Create INDEX test set S
/*for (i=1; i < 100000; i++) {
Db.s.insert ({' Number ': I, ' random ': Math.floor (Math.random () *i)})
}*/
Db.s.ensureindex ({' Random ': 1})
Db.s.find ({' number ': {' $gte ': +}}). sort ({' Random ': 1}). Limit (10)
Issues to consider when creating an index
1. What queries will be made, and which keys need to be indexed
2. What is the index direction of each key?
3, how to deal with the expansion
Inline document creation index is the same as document creation index
Db.blog.ensureIndex ({' Comments.name ': 1})
To create an index for a sort
Unique index/Composite index
Index name default: Keyname1_dir1 (random_1) Keynamex represents key, DirX represents ascending or descending
Name of the custom index
Db.c.ensureindex ({' X ': 1}, {' name ': ' X_index '})
Db.c.find ({' x ': {' $lt ':}}). Explain ()
Use explain to detect the time of the query/the number of rows affected/whether the index is used
Using hint to enforce indexing is not necessary in most cases
Cursor (basiccursor not using index/btreecursor x_1 using index)
Millis time to execute forecast (seconds) of course, the closer you get to 0, the better.
nscanned the number of documents executing the query
n the number of documents returned by execution
Index management
Database indexes are saved in the System.indexes collection
Db.system.indexes.find ()
Modification of the Index
Db.c.ensureindex ({' x ':-1}, {' name ': ' C_x_index ', ' Background ': true})
Use {' Background ': true} to enable this process to be performed in the background, and if not added then all requests will be blocked during indexing
Deletion of indexes
To delete the index of a database Liyang collection s
Db.s.getindexes ()
Db.s.dropindex (' random_1 ')
MongoDB Chapter Sixth Aggregation notes:
MongoDB provides a very powerful aggregation tool, simple statistics of the number of documents, complex can use MapReduce to do complex data analysis
Count ()
Db.s.count ()
Db.s.find ({' random ': {' $lte ': $, ' $gte ': 490}}). Count ()
Distinct is used to query out all the different values for a given key, and as with a relational database query, you must specify the collection and key
/*
Db.people.remove ()
for (I=1; i <; i++) {
Db.people.insert ({' Age ': I, ' name ': ' X ' +i})
}
Single build to get different values
Db.runcommand ({' distinct ': ' People ', ' key ': ' Age '})
*/
Group
Db.g.insert ({' user_id ': 1, ' Coin ': 5})
Db.g.insert ({' user_id ': 1, ' coin ': 15})
Db.g.insert ({' user_id ': 2, ' coin ': 15})
Db.g.insert ({' user_id ': 2, ' Coin ': 5})
/*
Db.runcommand ({
' Group ': {
' NS ': ' G ',
' Key ': ' user_id ',
' initial ': {' total ': 0},
' $reduce ': function (Doc, prev) {
Prev.total = Prev.total + doc.coin
}
}
})
*/
/*
Db.runcommand (
{
Aggregate: "G",
Pipeline: [
{$group: {_id: "$user _id", total: {$sum: "$coin"}},
{$sort: {total:-1}}
],
Explain:false
}
)
*/
NS to group the collection
Key documents are grouped by the keys, all the same key values will be divided into a set of
Initial the initial value of each group of reduce function calls
$reduce: Function (Doc, prev) {} Each document corresponds to this call, the system passes two parameters, the current document and the accumulator document
Condition user_id less than 3 documents
MapReduce is the star of aggregation, and count distinct group can implement
The cost of using MapReduce is that speed group is not fast, mapreduce is slower, and is seldom used
MongoDB Seventh Advanced Guide notes:
Using advanced features with database commands
---a fixed-size collection using a special collection
Using Gridfs to store files
Using MongoDB for JavaScript support
Understand what a database application is and when to use it
How Database commands work
Db.g.drop ()//returns TRUE or FALSE is actually
Db.runcommand ({' Drop ': ' G '})
Db.runcommand ({' Buildinfo ': 1})//return MongoDB version number and operating system
Db.runcommand ({' Collstats ': ' C '})//returns statistics for the specified collection
Db.runcommand ({' Drop ': ' Test '})//delete collection information errmsg
Db.runcommand ({' IsMaster ': 1})//query whether the server is a primary server or a server
Db.runcommand ({' ping ': 1})//Detect server connection is normal
Fixed collection
Fixed set is fixed size, like a ring collection, inserting new data resulting in insufficient space will delete the earlier information
The method of creating a fixed collection is not the same as a normal method you can specify the maximum number of documents for a collection and the total capacity of the collection
Db.createcollection (' gd ', {' capped ': true, ' size ': Ten, ' Max ': 100000})
Create a collection of 100,000 bytes with a maximum of 10 documents
Db.runcommand ({' collstats ': ' GD '})
Capped = True indicates that the collection size is fixed
Server-side scripting
Use Db.eval () to execute arbitrary JavaScript scripts
Db.eval (' Return 10+5 ')
Db.eval (' function () {return 1+4} ')
Note: The encapsulated function must be used only when passing parameters, and parameters are passed through the second parameter of Db.eval
Db.eval ("function (u) {return u;}", [' Apple '])//apple
Db.eval ("function (data) {return ' Hello, ' +data+ ';}", [' DFDF '])
Security
The implementation of JavaScript code, you must consider the security of MongoDB, the use of inadvertently occur similar to the injection of a relational database is an attack
For example, to print a user's username, the user name will be stored in a variable in the Username field.
var fun = "function (username) {return ' Hello ' +username+ '}"
Db.eval (fun, [' username '])
If the pass parameter ';d b.dropdatabase (); So the entire database will be cleaned up.
So we need to use placeholders to replace
MongoDB authoritative Guide to learning notes