MongoDB common commands and examples in detail (iii)

Source: Internet
Author: User

Introduction to common commands and their advanced commands


A: Detailed introduction of the advanced application of addition, deletion, modification and investigation:
Added: *** will be created automatically if c1 is absent when inserted ***
No matter which record is inserted, the primary key with a value id will be automatically increased.
insert and save (modify if id conflicts, otherwise insert)
One: the case of id primary key conflict does not differ
db.c1.insert ({name: "leyangjun"});
db.c1.insert ({name: "leyangjun"}); insert the value id is unique, there will be no primary key id conflict
db.c1.save ({name: "leyangjun"}); Same as insert, the id of the inserted record is the only primary key
Ranch
Two: id primary key conflict situation (conflict is updated)
db.c1.insert ({_ id: 1, name: "leyangjun2"});
db.c1.insert ({_ id: 1, name: "leyangjun2"}); When inserting the same value, an error will be reported
db.c1.save ({_ id: 1, name: "leyangjun3"}); --The insertion is successful, the ID conflict is updated, and idname = leyangjun2 is changed to leyangjun3
Ranch
You can also insert it like this (very flexible):
* It's better not to play like this, the consequence is that it will be troublesome for you to get the value when you use it in the php program.
db.c1.insert ({name: "user1", post: {tit: 1, cnt: 1111}}); --The value is a child JSON
db.c1.insert ({name: "user1", post: [1,2,3,4,5,6]});-the value is an array
Can be js json can also insert 10 loops:
for (i = 1; i <= 10; i ++) {
db.c1.insert ({name: "user" + i});
}
Delete:
db.c1.remove (); delete all == ({}) empty JSON, delete all json
db.c1.remove ({name: "user1"}); --Specify delete
Ranch
Check:
db.c1.find (); == (()) query all
db.c1.find ({name: "user3"}); conditional query
Ranch
Scenario: There are multiple columns in the record. As long as the specified column (but _id will be brought by default), the value is 1 and not 0.
db.c1.insert ({name: "leyangjun", age: 23, sex: "nan"});
db.c1.find ({name: "leyangjun"}, name: 1); only take this record name column
db.c1.find ({name: "leyangjun"}, name: 1, age: 1); take the name and age columns
db.c1.find ({name: "leyangjun"}, name: 1, _id: 0); don't use the default _id column
Ranch
Conditional expression query:
1): <, <=,>,> =-$ gt is greater than, $ lt is less than, $ gte is greater than or equal to, $ lte is less than or equal to
Insert 10 for testing
for (i = 1; i <= 10; i ++) {
db.c1.insert ({name: "user" + i, age: 1})
}
db.c1.find ({age: $ gt: 5}); $ gt older than 5 is greater than
db.c1.find ({age: $ lt: 5}); $ lt under age 5 is less than
db.c1.find ({age: $ gte: 5}); $ gte greater than or equal to 5 years old
db.c1.find ({age: $ lte: 5}); $ lte less than or equal to 5 years old
db.c1.find ({age: 5});
db.c1.find ({age: $ ne: 5});
Ranch
How many records are in it: db.c1.count (); or db.c1.find (). Count ();
Ranch
Sort by:
db.c1.find (). sort ({age: 1}) --- 1 means ascending
db.c1.find (). sort ({age: -1}) --- -1 is descending
Ranch
limit and combined with skip paging:
db.c1.find (). limit (3); --- Get 3 records from 0
db.c1.find (). skip (1) .limit (5); --- Skip one and get 5 (that is, start with the first few) 2,3,4,5,6
db.c1.find (). sort ({age: -1}). skip (1) .limit (5) .count (0); --- count statistics is 0 by default, regardless of the conditions written earlier, Just count a few
db.c1.find (). sort ({age: -1}). skip (1) .limit (5) .count (1); --- The number of records in the statistics according to the previous conditions
Ranch
2): $ all, find out that contains a certain value-mainly for arrays
db.c1.insert ({name: "user"}, post: [1,2,3,4,5,6]);
db.c1.find ({post: {$ all: [1,2,3]}}); --Find out if the post contains 1, 2, 3
Ranch
3): $ exists operation checks if a field exists
db.c1.find ((age: {$ exists: 1})); --- Check whether the field age is included
Ranch
4): $ mod balance
db.c1.find ((age: {$ mod: [2,1]})); --- Take 1, 2, 3, 5, 7, 9 ...
db.c1.find ((age: {$ mod: [2,0]})); --- take 2,4,6,8,10 ..... for the remainder of 2
Ranch
5): $ ne is not equal to
db.c1.find ({age: $ ne: 5});
Ranch
6): $ in and $ nin are similar to in in traditional relational databases, not in
db.c1.find ({age: {$ in: [1,3,5]}}); --- age equals 1,3,5 (is the array an operator)
b.c1.find ((age: {$ nin: [1,3,5]})); --- age is not equal to 1,3,5

* Law: [1,3,5] that appears generally when querying is an operator, not an array
7): $ or, $ nor (the two are opposite)
db.c1.find ({$ or: [{name: "user2"}, {name: "user3"}]}); --Find records with name = user2 or name = user3
db.c1.find ({$ nor: [{name: "user2"}, {name: "user3"}]}); --Filter out records with name = user2 and user3
Ranch
db.c1.find ({$ or: [{name: "user2"}, {age: 8}, {age: 10}]}); --find out names = user2 or age = 8 or age = 10 recording
db.c1.find ({$ nor: [{name: "user2"}, {age: 8}, {age: 10}]}); ---- Find name! = user2 or age! = 8 or age! = 10 records
Ranch
8): $ size find out the number of field array values-> special operations on the array
db.c1.insert ({name: "user1", post: [1,2,3,4,5,6]}); the first record
db.c1.insert ({name: "user1", post: [7,8,9]}); second record
db.c1.find ({post: $ size: 3}); --The second record will be found, and the number in the post is 3.
Ranch
9) **** Regular expression *******
And js regular:
db.c1.find ((name: / user / i)); --- find out if the name value contains user
Ranch
10): DISTINCT is similar to distinct in a relational database
db.c1.insert ({name: "leyangjun"});
db.c1.insert ({name: "leyangjun"});
db.c1.distinct ("name"); --- Duplicate the value and find a record
Ranch
11): $ elemMatch element match
db.c3.insert ({name: "user1", post: [{tit: 1}, {tit: 2}, {tit: 3}]});
db.c3.insert ({name: "user2", post: [{tit: "aaa"}, {tit: "bbb"}, {tit: "ccc"}]});
Ranch
Find records with tit = 2
db.c3.find ({"post.tit": 2}); --can be found
db.c3.find ((post: {$ elemMatch: tit: 2})); --match this way
db.c3.find ((post: ($ elemMatch: tit: 2, tit: 3)));-match records with tit = 2 tit = 3
Ranch
12): The concept of cursors (rarely used)
var x = db.c1.find ();
x.hasNext (); --If there is no value, it returns true and false. If true, go to the database to get the value, otherwise link to the database
x.next ()-get a value
x.next ()
x.next ()
x.next () --- always take down if there is a value
x.hasNext (); --- FALSE is worthless

13): null query (no value, value is empty, value is NULL)
Match age = null
db.c4.find ({age: null}); --- This match is inaccurate, and there is no age field in the record will be detected
db.c4.find ({age: {$ exists: 1, $ in: [null]}});-first determine whether the filter age exists, and match age = null
Or
db.c4.find ((age: $ type: 10)); --- 10 is null It is recommended to use this check null
db.c4.find ({age: $ type: 10, name: "user1"}); --age = null and name = user1
Ranch
14): $ slice-> only for arrays
db.c3.insert ({name: "user1", post: [{tit: 1}, {tit: 2}, {tit: 3}]});
db.c3.find ({name: "user1", {post: $ slice: 2}}); --- take name = user1, the first 2 posts are the value of the post field corresponding to the array: 1, 2,
db.c3.find ({name: "user1", {post: $ slice: -2}}); --- take name = user1, the last 2 posts are the value of the post field corresponding to the array: 2,3
db.c3.find ({name: "user1", {post: $ slice: [1,2]}}), --- Take 2 sticks from the first stick. Corresponding array: 2, 3
Ranch
Change:
update syntax introduction default is 0,0-the next 2 parameter values
db.collection.update (criteri
a, objNew, upsert, multi);
Parameter Description:
criteria: the object used to set the query criteria
objnew: used to set the updated content object
upsert: if the record already exists, update it, otherwise add a new record
multi: If there are multiple eligible records, all are updated
Note: By default, only the first eligible record will be updated.
Example:
db.c1.insert ({name: "leyangjun", age: 23);
db.c1.update ({name: "leyangjun"}, {sex: "nan"}); --This will delete the name and age, the record will only leave the sex field value
db.c1.update ({name: "user6"}, {name: "user66"}, 1); --1 means that if user6 exists, change to user66, otherwise user6 does not exist, add a new record name = user66
The 4th parameter can only be used in conjunction with the magic variable $ set, batch update
db.c1.update ({name: "user6"}, {$ set: {name: "user66"}}, 0,1);-update all user = name6 to user66
Ranch
2): $ set to add fields, or modify field values in batches (update if existing, increase if not)
db.c1.update ({name: "user6"}, {$ set: {name: "user66"}}, 0,1);-batch modify name values
db.c1.update ({name: "user10"}, {$ set: {age: 10}}, 0,1); --Add all the name = user1 to the age field, and the value = 10
Ranch
3): $ inc-> increment meaning self-increment, add or subtract if there is a field (self-defined), add if not
Scenario: Now in the promotion, I want to give 5 points to the members, but: some members of the points field does not have some
Now if you do n’t have a points field, you have to add 5 points.
db.c1.insert ({name: "leyangjun", age: 23, score: 11});
db.c1.insert ({name: "leyangjun", age: 23, score: 1});
db.c1.insert ({name: "leyangjun", age: 23});
-Plus points
db.c1.update ({}, {$ inc: score: 10}, 0,1);-{} means that all users add 10 points. If there is no score field, $ inc will be added uniformly.
db.c1.update ({name: "user1"}, {$ inc: score: 10}); plus or minus
db.c1.update ({name: "user1"}, {$ inc: score: -10});
Ranch
Both * set and $ inc can add fields, but the $ inc increase must be an integer
Ranch
4): $ unset delete field (built-in _id field can not be deleted)
db.c5.update ({}, {$ unset: {score: 1}, 0,1); --1 means true, delete the score field in all records
db.c5.update ((), ($ unset: (score: 1, age: 1), 0,1);-delete multiple
Ranch
5): $ push adds elements to the array (the magic method for updating is generally on the outside of the field, and the query is on the inside)
db.c3.insert ({name: "user1", arr: [1,2,3]});
db.c3.update ({name: "user1"}, {$ push: {arr: 4}}); --name = user1 increase the number of arr elements, remember that you cannot insert multiple at the same time (you can press the array, but you cannot (Push multiple values at the same time)
Ranch
6): $ pop removes the last element in the field, for arrays
db.c3.update ({name: "user1"}, {$ pop: {arr: 1}}); --1 means the last one, remove the last element in arr
db.c3.update ({name: "user1"}, {$ pop: {arr: -1}});--1 means delete the first value
7): $ pushAll push multiple values
db.c3.update ({name: "user1"}, {$ push: {arr: [4,5,6]}}); --- push multiple values
Ranch
8): $ addToSet will repeatedly insert the value (for example, there are 4 in the value, there will only be 4 in this insertion)
db.c3.update ({name: "user1"}, {$ addToSet: {arr: 4}}); --If there is 4 in the value, it cannot be inserted, and if there is no duplicate, insert
$ addToSet and $ each work together to insert multiple:
db.c3.update ({name: "user1"}, {$ addToSet: {arr: {$ each: [7,8,9]}}}); --Insert multiple
Ranch
9): $ pull delete a value in the array, for the array
db.c3.update ({name: "user1"}, {$ pull: {arr: 5}});-delete the value of 5 from the array
10): $ pullAll delete multiple at one time
db.c3.update ({name: "user1"}, {$ pullAll: {arr: [2,4]}});-delete value is 2,4
Ranch
11): $ rename modify the field name
db.c3.update ({name: "user1"}, {$ rename: {arr: "post"}}); or
db.c3.update ({name: "user1"}, {$ rename: {"arr": "post"}});
Ranch
12): Special operation symbol $
db.c3.insert ({name: "user1", arr: [{tit: "php"}, {tit: "java"}, {tit: "linux"}]});
Change the value titled linux:
db.c3.update ({"arr.tit": "linux"}, {$ set: {"arr. $. cnt": "linux is very good"}});
Ranch
Ranch
Ranch
*summary:
scene 1:
db.c1.insert ({name: "leyangjun", age: 23});
var x = find ({name: "user1"});
x-carriage return is valuable
x-no value in carriage return, so find itself has a cursor
Ranch
Scenario 2:
var x = findOne ({name: "user1"});
x --carriage return data x is a json, you can see the output when the mogodb client
x-carriage return and data
x.sex = "nan"-You can add fields, but the added fields will not be added directly to the data record
x.sex = "score"
...
Ranch
Save x plus field directly to database
db.c1.save (x);-the data is added to it,
Ranch
Ranch
Ranch
db.c1.insert ({name: "leyangjun", age: 23}); --- increase
db.c1.remove (); --- delete (remove all)
db.c1.remove ({"name": "leyangjun"});-delete records with names equal to leyangjun
db.c1.update ({name: "leyangjun"}, {name: "lekey"}); --- change, (if there is an age value, it will be deleted, leaving only the name value)
db.c1.update ({name: "leyangjun"}, {$ set: {name: "lekey"}}); --Change, this change will retain the original value
db.c1.update ({name: "lekey"}, {$ set: {sex: "nan"}}); --Can also increase the value, the name is equal to the lekey record to increase the field value sex
db.c1.find (); --- check
db.c1.find ({"name": "leyangjun"});

*** Difference between ordinary collection and fixed collection *****
Ordinary collections: The space of ordinary collections is automatically increased as the value of your json object increases.
Fixed collection: The maximum value of an append collection on a 32-bit machine is about 483.5M. On a 64-bit machine, it is limited only by the system size.
Ranch
2: capped collection (fixed collection)
Small command to remember birds:
show dbs;-show all databases
db-display the current database
show tables;-show all collections under the current library (that is, show all tables)
db.c5.drop (); --Delete c5 collection
db.dropDatabase ();
Ranch
Note: When you insert and enter mongodb, it will create a database and a collection (table) for you by default.
db.createCollection ("c1");-manually create a c1 collection (table)
db.c1.find ();
db.c1.drop ();
Ranch
basic introduction:
Capped collections are high-performance, fixed-size collections that use LRU (least recently used).
Rules and insertion order are processed by age-out (aging and removal), and the insertion order of objects in the collection is automatically maintained. The size must be executed in advance when creating.
. If space is used up, the newly added object will replace the oldest object in the collection.
Always up-to-date
Ranch
  Features:
Can be inserted and updated, but the update cannot exceed the size of the collection, otherwise the update fails.
It is not allowed to delete, but you can call drop () to delete all rows in the collection, but you need to explicitly rebuild the collection after the drop.
The maximum value of an append collection on a 32-bit machine is about 483.5M. On a 64-bit machine, it is limited only by the system size (that is, the system's limit on file size).
Ranch
Properties and methods: advantages
Attribute 1: Very fast inserts into fixed collections
Attribute 2: query output in insert order is extremely fast
Attribute 3: The ability to eliminate the oldest data when inserting the latest data
Ranch
Usage 1: Store log information
Usage 2: cache some small documents
Ranch
Create a fixed collection:
createCollection command to create
--size is set to 10M. If your file exceeds 10M, the file will be automatically deleted (the deletion rule is that the old data will be deleted once by analogy)
db.createCollection ("my_collection", {cappend: true, size: 10000000, max: 5});
Create a collection: ‘my_collection’ fixed collection with a size of 10000000 bytes. You can also limit the number of documents. Add the max: 100 attribute.
Ranch
Note: To specify a maximum document size, you must specify a size. The file limit is eliminated when the capacity is not full. If it is full, it is eliminated based on the capacity limit.
When you create the collection, it will automatically create the corresponding indexSize {"_ id _": xxxx} index id for you.
db.system.indexs.find ();-This will automatically form the primary key index for the collection you just created. Create the corresponding ID here.
Ranch
db.c1.stats (); --View the status value of collection C1, size, etc., index id or something
Note that there is a property: capped is 1 indicating that it is a fixed set
Common collection to fixed collection:
runCommand command
db.runCommand ({converToCapped: "c2", size: 10000000, max: 3});

Three: GridFS (large file upload and download, dedicated to storing pictures and videos)
Introduction: GridFS is a large binary storage in mongodb File mechanism, the reasons for using GridFS are the following:
-> Store huge files, such as videos, HD pictures
-> Using GridFS can simplify requirements
-> GridFS will directly use the established replication or sharding mechanism, and failure recovery and expansion are easy
-> GridFS can prevent users from uploading content files to cause system problems
-> GridFS does not produce disk fragmentation
Ranch
GridFS uses two tables to store data:
files contains metadata objects
chunks binary blocks containing some other relevant information
Ranch
* In order to name multiple GridFS as a single database, files and blocks have a prefix. By default, the prefix is fs,
So any default GridFS storage will contain fs.files and fs.chunks.
Various third room languages can change their prefix.
Ranch
Use GridFS mongofiles (where files are stored)
mongofiles is a tool for manipulating GridFS from numerology
Three commands: put (store) get (get, download) list (list)
Ranch
Example:
./mongofiles -h-View supported basic parameters
./mongofiles list-view all files in mongofiles
Ranch
Now simulate dropping a file into it
tar czf mongosniff.tar.gz mongosniff-compress mongosniff files into packages
./mongofiles put mongosniff.tar.gz-upload the package file
Ranch
After you can enter mongo
./mongo
show tables;-you will find 2 more sets fs.files, fs.chunks
db.fs.files.find (); --View
--The corresponding field description appears:
filename: the name of the stored file
chunkSize: the size of chunks
uplodaDate: storage time
md5: md5 code of this file
length: file size in bytes
fs.files stores some basic metadata information, the real content is in fs.chunks
Ranch
db.fs.chunks.find (); --The real file is in it
exit;
Ranch
./mongofiles list-you can see the files we put on
./mongofiles get mongosniff.tar.gz-Download this file and download it to the directory where you are currently executing the command
./mongofiles delete mongosniff.tar.gz-delete the file
* Note: When you delete files under mongofiles, there is nothing under the fs.files and fs.chunks tables
Ranch
Ranch
Ranch
Four: performance
1: Index Management
mongodb provides diversified index support. Index information is stored in system.indexs. The _id field in mongodb is in
When created, an index has been created by default. This index is special and cannot be deleted, but outside the capped collection column.
1: Indexing
1: ordinary index
for (i = 1; i <= 10; i ++) {
db.c1.insert ({name: "user" + i, age: i});
}
db.c1.find ({name: "user5"}). explain (); --explain parses a statement in the same way as MySQL. It can be seen that the entire table is scanned without an index.
Ranch
1 is ascending (default) -1 is descending
db.c1.ensureIndex ({name: 1});
db.c1.ensureIndex ({name: 1}, {background: true}); --If the data is time-consuming, put it in the background for execution, and add the second parameter, which means it is put in the background
db.c1.getIndexKeys (); --View all fields Simple information
db.c1.getIndexes ()-view table index details
Ranch
db.c1.find ({name: "user5"}). explain (); --After indexing, you will find that only one row will be scanned, not the entire table.
2: unique index
db.c1.ensureIndex ((age: 1), unique: 1); --age field establishes a unique index
db.c1.insert ({name: "user11", age: 10});-you will find that you cannot insert it, thinking that age is the only index
Ranch
2: View the index
db.c1.getIndexKeys (); --View all fields Simple information
db.c1.getIndexes ()-view table index details
Ranch
Ranch
3: delete index
db.c1.dropIndexes (); --Delete all indexes _id cannot be deleted
db.c1.dropIndex ((name: 1)); --Specify the drop index
Ranch
Two: performance optimization
explain execution plan (see number of affected rows)
mongodb provides an explain command to let us know how the system handles query requests, using the explain command
We can very well observe how the system uses the index to speed up retrieval, and at the same time, it can optimize the index.
Ranch
Optimizer profile (similar to MySQL's slow query log)
Disabled by default and 100 milliseconds by default
db.getProfilingLevel (); --0 If 0, it means that the slow query log is not enabled
db.setProfilingLevel (1); --1 means to enable the record slow query (default is 100ms)
--2 means record all commands
Ranch
db.setProfilingLevel (1,1000);-the first way: the second parameter is the setting time milliseconds
-The second way: bring --slowms setting when starting mongodb
Ranch
mongodb optimization scheme:
1: create an index
2: Limit the number of results returned
3: query the fields used, not all fields
4: Use capped collection
Capped collections have higher read and write efficiency than ordinary collections
5: Slow query log with profiling
Ranch
Ranch
Ranch
Three performance monitoring (2 tools included)
1: mongosniff records communication records
Open 2 windows
./mongosniff --source net lo A window execution
Ranch
./mongo --B window is linked to mongodb. After being able to, window A has already recorded the operation information of B, log in, log out, etc.
Ranch
Ranch
2: mongostat monitoring (who visits, deletes ...)
./mongostat --A window execution, will refresh the interface every second
./mongo --B window is linked to mongodb, the records of additions, deletions and checks performed by B will be monitored in window A
Ranch

Later update MongoDB advanced knowledge


Related Article

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.