Query:
MySQL:
Select * from user
Mongo:
DB. User. Find ()
MySQL:
Select * from user where name = 'starlil'
Mongo:
DB. User. Find ({'name': 'starlil '})
Insert:
MySQL:
Insert inot user ('name', 'age') values ('starlil', 25)
Mongo:
DB. User. insert ({'name': 'starlee ', 'age': 25 })
To add a field to MySQL, you must:
Alter table user ....
However, in MongoDB, you only need:
DB. User. insert ({'name': 'starlee ', 'age': 25, 'email': 'starlee @ starlee.com '})
Delete:
MySQL:
Delete * from user
Mongo:
DB. User. Remove ({})
MySQL:
Delete from user where age <30
Mongo:
DB. User. Remove ({'age': {$ LT: 30 }})
$ GT: >;$ GTE: >=;$ lt :<;$ LTE :<=; $ ne :! =
Update:
MySQL:
Update user set 'age' = 36 where 'name' = 'starlil'
Mongo:
DB. User. Update ({'name': 'starlil'}, {$ set: {'age': 36 }})
MySQL:
Update user set 'age' = 'age' + 3 where 'name' = 'starlil'
Mongo:
DB. User. Update ({'name': 'starlil'}, {$ Inc: {'age': 3 }})
MySQL:
Select count (*) from user where 'name' = 'starlil'
Mongo:
DB. User. Find ({'name': 'starlil'}). Count ()
MySQL:
Select * from user limit 10, 20
Mongo:
DB. User. Find (). Skip (10). Limit (20)
MySQL:
Select * from user where 'age' in (25, 35, 45)
Mongo:
DB. User. Find ({'age': {$ in: [25, 35, 45]})
MySQL:
Select * from user order by age DESC
Mongo:
DB. User. Find (). Sort ({'age':-1 })
MySQL:
Select distinct (name) from user where age> 20
Mongo:
DB. User. Distinct ('name', {'age': {$ LT: 20 }})
MySQL:
Select name, sum (marks) from user group by name
Mongo:
DB. User. Group ({
Key: {'name': true },
Cond: {'name': 'foo '},
Reduce: function (OBJ, Prev) {Prev. msum + = obj. Marks ;},
Initial: {msum: 0}
});
MySQL:
Select name from user where age <20
Mongo:
DB. User. Find ('this. age <20', {Name: 1 })
Many people found that they are searching for MongoDB to insert data cyclically. The following describes how to insert data cyclically in MongoDB:
For (VAR I = 0; I <100; I ++) dB. Test. insert ({uid: I, uname: 'nosqlfan '+ I });
Insert one hundred data records at a time. The approximate structure is as follows:
{"_ ID": objectid ("4c876e519e86023a30dde6b8"), "uid": 55, "uname": "nosqlfan55 ″}
{"_ ID": objectid ("4c876e519e86023a30dde6b9"), "uid": 56, "uname": "nosqlfan56 ″}
{"_ ID": objectid ("4c876e519e86023a30dde6ba"), "uid": 57, "uname": "nosqlfan57 ″}
{"_ ID": objectid ("4c876e519e86023a30dde6bb"), "uid": 58, "uname": "nosqlfan58 ″}
{"_ ID": objectid ("4c876e519e86023a30dde6bc"), "uid": 59, "uname": "nosqlfan59 ″}
{"_ ID": objectid ("4c876e519e86023a30dde6bd"), "uid": 60, "uname": "nosqlfan60 ″}
Simple comparison table
SQL statement Mongo query language statement
Create Table users (a number, B Number) implicit; can be done explicitly
Insert into users values (1, 1) dB. Users. insert ({A: 1, B: 1 })
Select a, B from users dB. Users. Find ({}, {A: 1, B: 1 })
Select * from users dB. Users. Find ()
Select * from users where age = 33 dB. Users. Find ({age: 33 })
Select a, B from users where age = 33 dB. Users. Find ({age: 33}, {A: 1, B: 1 })
Select * from users where age = 33 order by name dB. Users. Find ({age: 33}). Sort ({Name: 1 })
Select * from users where age> 33 dB. Users. Find ({'age' :{$ GT: 33 }})})
Select * from users where age <33 dB. Users. Find ({'age' :{$ LT: 33 }})})
Select * from users where name like "% Joe %" DB. Users. Find ({Name:/Joe /})
Select * from users where name like "Joe %" DB. Users. Find ({Name:/^ Joe /})
Select * from users where age> 33 and age <= 40 dB. Users. Find ({'age': {$ GT: 33, $ LTE: 40 }})})
Select * from users order by name DESC dB. Users. Find (). Sort ({Name:-1 })
Create index myindexname on users (name) dB. Users. ensureindex ({Name: 1 })
Create index myindexname on users (name, ts desc) dB. Users. ensureindex ({Name: 1, TS:-1 })
Select * from users where a = 1 and B = 'q' dB. Users. Find ({A: 1, B: 'q '})
Select * from users limit 10 skip 20 dB. Users. Find (). Limit (10). Skip (20)
Select * from users where a = 1 or B = 2 dB. Users. Find ({$ or: [{A: 1 },{ B: 2}]})
Select * from users limit 1 dB. Users. findone ()
Explain select * from users where z = 3 dB. Users. Find ({z: 3}). Explain ()
Select distinct last_name from users dB. Users. Distinct ('Last _ name ')
Select count (* Y) from users dB. Users. Count ()
Select count (* Y) from users where age> 30 dB. Users. Find ({age: {'$ GT': 30}). Count ()
Select count (AGE) from users dB. Users. Find ({age: {'$ exists': true}). Count ()
Update users set a = 1 Where B = 'q' dB. users. update ({B: 'q'}, {$ set: {A: 1 }}, false, true)
Update users set a = a + 2 Where B = 'q' dB. users. update ({B: 'q'}, {$ Inc: {A: 2 }}, false, true)
Delete from users where z = "ABC" DB. Users. Remove ({z: 'abc '});
######################################## ###########
I. Operators
Operators are certainly known to all. They are equal to, greater than, less than, not equal to, greater than or equal to, and less than or equal to. However, they cannot be used directly in MongoDB. The operators in MongoDB are represented as follows:
(1) $ GT> (greater)
(2) $ lt <(less)
(3) $ GTE >=( greater than or equal)
(4) $ lt <= (less than or equal)
(5) $ ne! = (Not equal)
(6) $ in (inclusive)
(7) $ Nin not in (not included)
(8) $ exists exist (whether the field exists)
(9) $ Inc adds value to a numeric field
(10) $ set is equivalent to SQL's set field = value.
(11) $ unset indicates deleting a field.
(12) $ push append the value to the field. The field must be of the array type. If the field does not exist, a new array type will be added.
(13) $ pushall is the same as $ push, but multiple values can be appended to an array field at a time.
(14) $ addtoset adds a value to the array and increases only when the value is not in the array.
(15) $ pop Delete the last value: {$ POP: {field: 1} Delete the first value: {$ POP: {field:-1}. Note, only one value can be deleted, that is, only 1 or-1 can be used, and 2 or-2 cannot be used to delete two values. MongoDB 1.1 and later versions are available
(16) $ pull deletes a value equal to the value from the array Field
(17) $ pullall is the same as $ pull. Multiple values in the array can be deleted at a time.
(18) The $ operator is his own meaning, which indicates a certain item in the array identified by conditions. This is not enough.
Ii. Adding, modifying, reading, and deleting Curd
Add
Copy codeThe Code is as follows: DB. Collection-> insert ({'name' => 'caleng', 'email '=> 'admin # admin.com '});
Isn't it easy? It's so simple. It has no field restrictions. you can name it and insert data at will.
Modify Copy codeThe Code is as follows: DB. collection. update ({"count": {$ GT: 1 }},{ $ set: {"Test2": "OK"}); only the first record greater than 1 is updated.
DB. collection. update ({"count": {$ GT: 3 }},{ $ set: {"Test2": "OK" }}, false, true ); all records greater than 3 have been updated.
DB. collection. update ({"count": {$ GT: 4 }},{ $ set: {"test5": "OK" }}, true, false ); only the first record with a value greater than 4 is added.
DB. collection. update ({"count": {$ GT: 5 }},{ $ set: {"test5": "OK" }}, true, true ); more than 5 records are added
Query Copy codeThe Code is as follows: DB. collection. Find (Array ('name' => 'bailing'), array ('email '=> 'email @ QQ.com '))
DB. collection. findone (Array ('name' => 'bailing'), array ('email ''email @ QQ.com '))
You can see that I have used two different ways to query the logs. Why? In fact, this is the same as cooking. different spices are used and the fried dishes have different tastes. The following describes the different effects of the two spices.
Findone () returns only one document object, and find () returns a list of sets.
That is to say, if we only want to query the details of a specific data, we can use findone ();
If you want to query a group of information, such as a news list, we can use find ();
So I think everyone will think that I want to sort this list. No problem MongoDB will serve you wholeheartedly.Copy codeThe Code is as follows: DB. collection. Find (). Sort ({age: 1}); // sort by age in the forward order
DB. collection. Find (). Sort ({age:-1}); // sort by age in reverse order
DB. collection. Count (); // obtain the total number of data.
DB. collection. limit (1); // the starting position of the data.
DB. collection. Skip (10); // The end position of the retrieved data.
// In this way, we implement a sorting operation for 10 pieces of data.
Delete
Delete has two operations: Remove () and drop ()Copy codeThe Code is as follows: DB. collection. Remove ({"name", 'Jerry '}) // delete specific data
DB. collection. Drop () // delete all data in the Set
Distinct operationCopy codeThe Code is as follows: DB. User. Distinct ('name', {'age' :{$ LT: 20 }})
######################################## ###
2. Familiar with MongoDB data operation statements, such as SQL
Database Operation syntax
Mongo -- path
DB. adduser (username, password) Add User
DB. Auth (usrename, password) sets database connection Verification
DB. clonedatabase (fromhost) clone a database from the target server
DB. commandhelp (name) returns the help for the command
DB. copydatabase (fromdb, todb, fromhost) copy the database fromdb --- source database name, todb --- target database name, fromhost --- source database server address
DB. createcollection (name, {size: 3333, capped: 333, Max: 88888}) to create a dataset, equivalent to a table
DB. currentop () cancels the current operation of the current database
DB. dropdatabase () Delete the current database
DB. eval (func, argS) run code server-side
DB. getcollection (cname) obtains a data set. The same usage is DB ['cname'] or db. cname.
DB. getcollenctionnames () Get the name list of all data sets
DB. getlasterror () returns the message indicating the last error.
DB. getlasterrorobj () returns the last error object
DB. getmongo () gets the connection object of the current server get the server connection object
DB. getmondo (). setslaveok () allow this connection to read from then nonmaster membr of a replica pair
DB. getname () returns the name of the database to be operated on.
DB. getpreverror () returns the previous error object
DB. getprofilinglevel ()? Level
DB. getreplicationinfo ()? What information
DB. getsisterdb (name) Get the dB at the same server as this onew
DB. Killop () Stop (kill) the current operation in the current database
DB. printcollectionstats () returns the dataset status of the current database
DB. printreplicationinfo ()
DB. printslavereplicationinfo ()
DB. printshardingstatus () returns whether the current database is a shared database
DB. removeuser (username) delete a user
DB. repairdatabase () repairs the current database
DB. reseterror ()
DB. runcommand (cmdobj) run a database command. If cmdobj is a string, turns it into {cmdobj: 1}
DB. setprofilinglevel (level) 0 = OFF, 1 = slow, 2 = all
DB. shutdownserver () Close the current service program
DB. Version () returns the version information of the current program.
Dataset (table) operation syntax
DB. Linlin. Find ({ID: 10}) returns the Linlin dataset id = 10
DB. Linlin. Find ({ID: 10}). Count () returns the total number of data records with Linlin dataset id = 10.
DB. Linlin. Find ({ID: 10}). Limit (2) returns the dataset whose Linlin dataset id = 10 starts from the second one.
DB. Linlin. Find ({ID: 10}). Skip (8) returns the data set of the Linlin dataset id = 10 from 0 to the eighth.
DB. Linlin. Find ({ID: 10}). Limit (2). Skip (8) returns the data of the Linlin dataset id = 1 = from the second to the eighth.
DB. Linlin. Find ({ID: 10}). Sort () returns the sorted dataset with the Linlin dataset id = 10.
DB. Linlin. findone ([query]) returns a data record that meets the condition.
DB. Linlin. getdb () returns the name of the database to which the dataset belongs.
DB. Linlin. getindexes () returns index information for some datasets.
DB. Linlin. Group ({key:..., initial:..., reduce:... [, Cond:...]})
DB. Linlin. mapreduce (mayfunction, performancefunction, <optional Params>)
DB. Linlin. Remove (query) deletes a piece of data in the dataset.
DB. Linlin. renamecollection (newname) rename some dataset names
DB. Linlin. Save (OBJ) inserts a data entry into the dataset.
DB. Linlin. Stats () returns the status of this dataset
DB. Linlin. storagesize () returns the storage size of this dataset.
DB. Linlin. totalindexsize () returns the size of the index file for this dataset.
DB. Linlin. totalsize () returns the total size of some datasets.
DB. Linlin. Update (query, object [, upsert_bool]) updates a piece of data in this dataset.
DB. Linlin. Validate () verifies this dataset
DB. Linlin. getshardversion () returns the shared version of the dataset.