Detailed description of simple comparison table from MySQL to MongoDB

Source: Internet
Author: User
Tags findone

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.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 operation
Copy 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.

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.