Detailed _php example of simple comparison table based on MySQL to MongoDB

Source: Internet
Author: User
Tags comparison table create index findone mongodb prev
Inquire:
Mysql:
SELECT * from user
Mongo:
Db.user.find ()
MySQL:
SELECT * FROM user WHERE name = ' Starlee '
Mongo:
Db.user.find ({' name ': ' Starlee '})
Insert:
Mysql:
INSERT inot User (' name ', ' age ') VALUES (' Starlee ', 25)
Mongo:
Db.user.insert ({' name ': ' Starlee ', ' Age ': 25})
If you want to add a field to MySQL, you must:
ALTER TABLE user ....
But in MongoDB you only need to:
Db.user.insert ({' name ': ' Starlee ', ' age ':, ' 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 ' = + WHERE ' name ' = ' Starlee '
Mongo:
Db.user.update ({' name ': ' Starlee '}, {$set: {' age ': 36}}})
MySQL:
UPDATE user SET ' age ' = ' age ' + 3 WHERE ' name ' = ' Starlee '
Mongo:
Db.user.update ({' name ': ' Starlee '}, {$inc: {' Age ': 3}}})
Mysql:
SELECT COUNT (*) from user WHERE ' name ' = ' Starlee '
Mongo:
Db.user.find ({' name ': ' Starlee '}). Count ()
MySQL:
SELECT * from user limit 10,20
Mongo:
Db.user.find (). Skip (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} ')
Found that a lot of people in the search MongoDB loop inserts the data, the following method of inserting the MongoDB into the data is added below:
for (Var i=0;i<100;i++) Db.test.insert ({uid:i,uname: ' Nosqlfan ' +i});
Insert 100 data at a single, probably structure as follows:
{"_id": ObjectId ("4c876e519e86023a30dde6b8″"), "UID": "," uname ":" Nosqlfan55″}
{"_id": ObjectId ("4c876e519e86023a30dde6b9″"), "UID":, "uname": "Nosqlfan56″}"
{"_id": ObjectId ("4c876e519e86023a30dde6ba"), "UID": *, "uname": "Nosqlfan57″}"
{"_id": ObjectId ("4C876E519E86023A30DDE6BB"), "UID": "," uname ":" Nosqlfan58″}
{"_id": ObjectId ("4C876E519E86023A30DDE6BC"), "UID": "A", "uname": "Nosqlfan59″}"
{"_id": ObjectId ("4C876E519E86023A30DDE6BD"), "UID": "A", "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 the 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 the users WHERE name like "%joe%" Db.users.find ({name:/joe/})
SELECT * from the users WHERE name like "joe%" Db.users.find ({name:/^joe/})
SELECT * from the users WHERE age>33 and age<=40 db.users.find ({' age ': {$gt: $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 db.users.find (). LIMIT (a). 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 the Users where > db.users.find ({age: {' $gt ':}}). Count ()
SELECT count (age) from the 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 '});
###################################################
First, operator
Operators believe that we must all know, is equal to, greater than, less than, not equal to, greater than equals, less than equal, but in the MongoDB can not directly use these operators. The operator in the MongoDB is represented as this:
(1) $gt > (greater than)
(2) $lt < (less than)
(3) $gte >= (greater than or equal)
(4) $lt <= (less than equal)
(5) $ne!= (not equal to)
(6) $in in (inclusive)
(7) $nin not in (does not contain)
(8) $exists exist (whether the field exists)
(9) $inc Add Value To Field field of a number
(Ten) $set is the equivalent of the SQL set field = value
(one) $unset is to delete the field
(a) $push Append value To field, field must be an array type, if field does not exist, add an array type
($PUSHALL) with $push, just one time you can append multiple values to an array field
$addToSet adds a value to the array and increases only if the value is not in the array.
($pop Delete last value: {$pop: {field:1}}} Delete first value: {$pop: {field:-1}} Note that only one value can be deleted, that is, only 1 or 1, and two can not be deleted with 2 or-two. MongoDB 1.1 and later versions are only available.
($pull) deletes one equal value value from the array field
($PULLALL) with $pull, you can delete multiple values within an array at one time
(18) The $ operator is his own meaning, which represents an array of conditions found within himself. This compares to the AO mouth, does not say.
ii. Increase, change, read and delete of curd
Increase
Copy Code code as follows:

Db.collection->insert ({' name ' => ' Caleng ', ' email ' => ' admin#admin.com '});

is not gray often simple yes, it is so simple, it has no field restrictions, you can arbitrarily name, and insert data
Copy Code code as follows:

Db.collection.update ({"Count": {$gt: 1}}, {$set: {"test2": {"OK"}}); Only the first record greater than 1 was updated
Db.collection.update ({"Count": {$gt: 3}}, {$set: {"test2": "OK"}},false,true); Records greater than 3 are fully updated
Db.collection.update ({"Count": {$gt: 4}}, {$set: {"Test5": "OK"}},true,false); Records larger than 4 are added to the first one.
Db.collection.update ({"Count": {$gt: 5}}, {$set: {"Test5": "OK"}},true,true); All records greater than 5 are added.

Query
Copy Code code as follows:

Db.collection.find (Array (' name ' => ' bailing '), array (' email ' => ' email@qq.com '))
Db.collection.findOne (Array (' name ' => ' bailing '), array (' email ' ' email@qq.com '))

We can see the query I used two different ways of writing, this is why, in fact, this is the same as cooking, put different spices, fried dishes are different flavor. Here are some of the different effects of the two spices.
FindOne () returns only one document object, and find () returns a list of collections.
That is to say, for example, we only want to check a specific data of the details, we can use FindOne ();
If you want to query a group of information, such as a news list, we can act find ();
Then I think everyone will think that I want to sort this list, no problem MongoDB will serve you wholeheartedly
Copy Code code as follows:

Db.collection.find (). Sort ({age:1}); Arrange by age in positive order
Db.collection.find (). Sort ({age:-1}); Arrange by age in reverse order
Db.collection.count (); Get the total number of data
Db.collection.limit (1); Start position of data
Db.collection.skip (10); Take the end position of the data
This allows us to implement a 10-piece data, and sort the operation.

Remove
Delete has two actions remove () and drop ()
Copy Code code as follows:

Db.collection.remove ({"Name", ' Jerry '})//delete specific data
Db.collection.drop ()//delete all data in the collection

DISTINCT operation
Copy Code code as follows:

Db.user.distinct (' name ', {' age ': {$lt: 20}})

2. Familiar with MongoDB data manipulation statements, class SQL
Database operation syntax
MONGO--path
Db. AddUser (username,password) Add user
Db.auth (Usrename,password) Set up database connection verification
Db.clonedatabase (fromhost) clones a database from the target server
DB.COMMANDHELP (name) returns the Help for the command
Db.copydatabase (fromdb,todb,fromhost) Copy database fromdb---Source database name, TODB---target database name, fromhost---source database server address
Db.createcollection (name,{size:3333,capped:333,max:88888}) creates a dataset that is equivalent to a table
Db.currentop () cancels the current operation of the current library
Db.dropdatabase () deletes the current database
Db.eval (Func,args) Run code server-side
Db.getcollection (CNAME) obtains a data collection, same usage: db[' cname '] or db.cname
Db.getcollenctionnames () Gets the list of names for all data sets
Db.getlasterror () returns a prompt message for the last error
Db.getlasterrorobj () Returns the object of the last error
Db.getmongo () Gets the current server's connection object 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 operation database
Db.getpreverror () returns the previous Error object
Db.getprofilinglevel () What grade?
Db.getreplicationinfo () What's the message?
DB.GETSISTERDB (name) get the DB in the same server as this onew
Db.killop () Stop (kill) The current operation in the current library
Db.printcollectionstats () returns the dataset state of the current library
Db.printreplicationinfo ()
Db.printslavereplicationinfo ()
Db.printshardingstatus () returns whether the current database is a shared database
Db.removeuser (username) Delete User
Db.repairdatabase () repair 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 () Closes 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 DataSet id=10 the Linlin dataset
Db.linlin.find ({id:10}). Count () returns the total number of data Linlin the dataset id=10
Db.linlin.find ({id:10}). Limit (2) returns a DataSet from the second set of Datasets id=10 by the Linlin dataset
Db.linlin.find ({id:10}). Skip (8) Returns a dataset id=10 a dataset from 0 to eighth in a dataset of Linlin datasets
Db.linlin.find ({id:10}). Limit (2). Skip (8) returns data from article II to eighth of the dataset id=1= data set Linlin
Db.linlin.find ({id:10}). Sort () returns the sorted data set id=10 the Linlin dataset
Db.linlin.findOne ([query]) returns one piece of data that matches the criteria
Db.linlin.getDB () returns the name of the database to which this dataset belongs
Db.linlin.getIndexes () returns index information for some datasets
Db.linlin.group ({key:...,initial:...,reduce: ...) [, cond: ...]})
Db.linlin.mapReduce (mayfunction,reducefunction,<optional params>)
Db.linlin.remove (query) deletes a piece of data in a dataset
Db.linlin.renameCollection (newName) rename some dataset names
Db.linlin.save (obj) inserts a piece of data into the dataset
Db.linlin.stats () Returns the state of this dataset
Db.linlin.storageSize () returns the storage size of this dataset
Db.linlin.totalIndexSize () returns the index file size of this dataset
Db.linlin.totalSize () returns the total size of some datasets
Db.linlin.update (Query,object[,upsert_bool]) update a piece of data in this dataset
Db.linlin.validate () validates this dataset
Db.linlin.getShardVersion () returns the dataset share version number
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.