Cheat Sheet: From SQL to NoSQL


Recently I was fascinated by MongoDB’s flexibility to change data structure on the fly, in contrast there will need a ALT TABLE SQL statement for any schema change in a SQL database. Here I make a list of typical operations and how they are done in both SQL and NoSQL(in my case, MongoDB) flavours.

Create and use a database

# MySQL: 
CREATE DATABASE mydb; USE mydb
# MongoDB: a database in MongoDB will be created automatically
use mydb

Create and drop a table/collection

# MySQL: 
CREATE TABLE mytable (
	id int primary PRIMARY KEY AUTO_INCREMENT,
    name varchar(200),
    ...
);
DROP TABLE mytable;
# MongoDB: it's called a collection in MongoDB
# and since it's a document database, no schema is needed for a new collection
db.createCollection('mycollection')
db.mycollection.drop()

Insert a row/document

# MySQL:
INSERT INTO mytable (name, email) VALUES ('John', '[email protected]')
# MongoDB:
db.mycollection.insertOne({name: 'John', email: '[email protected]'})
# MongoEngine
from mongoengine import Document, fields
class mycollection(Document):
	name = fields.StringField()
    email = fields.StringField()
doc = mycollection(name='John', email='[email protected]')
doc.save()

Select a row/document

# MySQL:
SELECT * FROM mytable WHERE name='John';
# MongoDB:
db.mycollection.find({name: 'John'})
# MongoEngine
mycollection.objects.get(name='John')

Select using Regex

# MySQL:
SELECT * FROM mytable WHERE name REGEXP '^Jo'
# MongoDB:
db.mycollection.find({name: /^Jo/})
# MongoEngine:
mycollection.objects(name__regex='^Jo')

More examples are coming…