Reprinted from nosqlfan. view the original article
This article describes how to write common SQL statements in MySQL in MongoDB. If you are eager to try using MySQL for a long time, this simple article will help you enter the role more quickly.
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 ("Comment ″), "uid": 56, "uname": "nosqlfan56"} {"_ ID": objectid ("4c876e519e86023a30dde6ba"), "uid": 57, "uname ": "nosqlfan57"} {"_ ID": objectid ("4c876e519e86023a30dde6bb"), "uid": 58, "uname": "nosqlfan58"} {"_ ID ": objectid ("identifier"), "uid": 59, "uname": "nosqlfan59"} {"_ ID": objectid ("4c876e519e86023a30dde6bd"), "uid": 60, "uname": "nosqlfan60 ″}