SQL to MongoDB Mapping Chart

In addition to the charts that follow, you might want to consider the Frequently Asked Questions section for a selection of common questions about MongoDB.

Terminology and Concepts

The following table presents the various SQL terminology and concepts and the corresponding MongoDB terminology and concepts.

SQL Terms/Concepts MongoDB Terms/Concepts
database database
table collection
row document or BSON document
column field
index index
table joins embedded documents and linking

primary key

Specify any unique column or column combination as primary key.

primary key

In MongoDB, the primary key is automatically set to the_id field.

aggregation (e.g. group by)

aggregation pipeline

See the SQL to Aggregation Mapping Chart.

Executables

The following table presents some database executables and the corresponding MongoDB executables. This table is not meant to be exhaustive.

  MongoDB MySQL Oracle Informix DB2
Database Server mongod mysqld oracle IDS DB2 Server
Database Client mongo mysql sqlplus DB-Access DB2 Client

Examples

The following table presents the various SQL statements and the corresponding MongoDB statements. The examples in the table assume the following conditions:

  • The SQL examples assume a table named users.

  • The MongoDB examples assume a collection named users that contain documents of the following prototype:

    {
    _id: ObjectId("509a8fb2f3f4948bd2f983a0"),
    user_id: "abc123",
    age: 55,
    status: 'A'
    }

Create and Alter

The following table presents the various SQL statements related to table-level actions and the corresponding MongoDB statements.

SQL Schema Statements MongoDB Schema Statements
CREATE TABLE users (
id MEDIUMINT NOT NULL
AUTO_INCREMENT,
user_id Varchar(30),
age Number,
status char(1),
PRIMARY KEY (id)
)

Implicitly created on first insert() operation. The primary key _id is automatically added if _id field is not specified.

db.users.insert( {
user_id: "abc123",
age: 55,
status: "A"
} )

However, you can also explicitly create a collection:

db.createCollection("users")
ALTER TABLE users
ADD join_date DATETIME

Collections do not describe or enforce the structure of its documents; i.e. there is no structural alteration at the collection level.

However, at the document level, update() operations can add fields to existing documents using the $set operator.

db.users.update(
{ },
{ $set: { join_date: new Date() } },
{ multi: true }
)
ALTER TABLE users
DROP COLUMN join_date

Collections do not describe or enforce the structure of its documents; i.e. there is no structural alteration at the collection level.

However, at the document level, update() operations can remove fields from documents using the $unset operator.

db.users.update(
{ },
{ $unset: { join_date: "" } },
{ multi: true }
)
CREATE INDEX idx_user_id_asc
ON users(user_id)
db.users.createIndex( { user_id: 1 } )
CREATE INDEX
idx_user_id_asc_age_desc
ON users(user_id, age DESC)
db.users.createIndex( { user_id: 1, age: -1 } )
DROP TABLE users
db.users.drop()

For more information, see db.collection.insert()db.createCollection(),db.collection.update()$set$unsetdb.collection.createIndex()indexes,db.collection.drop(), and Data Modeling Concepts.

Insert

The following table presents the various SQL statements related to inserting records into tables and the corresponding MongoDB statements.

SQL INSERT Statements MongoDB insert() Statements
INSERT INTO users(user_id,
age,
status)
VALUES ("bcd001",
45,
"A")
db.users.insert(
{ user_id: "bcd001", age: 45, status: "A" }
)

For more information, see db.collection.insert().

Select

The following table presents the various SQL statements related to reading records from tables and the corresponding MongoDB statements.

SQL SELECT Statements MongoDB find() Statements
SELECT *
FROM users
db.users.find()
SELECT id,
user_id,
status
FROM users
db.users.find(
{ },
{ user_id: 1, status: 1 }
)
SELECT user_id, status
FROM users
db.users.find(
{ },
{ user_id: 1, status: 1, _id: 0 }
)
SELECT *
FROM users
WHERE status = "A"
db.users.find(
{ status: "A" }
)
SELECT user_id, status
FROM users
WHERE status = "A"
db.users.find(
{ status: "A" },
{ user_id: 1, status: 1, _id: 0 }
)
SELECT *
FROM users
WHERE status != "A"
db.users.find(
{ status: { $ne: "A" } }
)
SELECT *
FROM users
WHERE status = "A"
AND age = 50
db.users.find(
{ status: "A",
age: 50 }
)
SELECT *
FROM users
WHERE status = "A"
OR age = 50
db.users.find(
{ $or: [ { status: "A" } ,
{ age: 50 } ] }
)
SELECT *
FROM users
WHERE age > 25
db.users.find(
{ age: { $gt: 25 } }
)
SELECT *
FROM users
WHERE age < 25
db.users.find(
{ age: { $lt: 25 } }
)
SELECT *
FROM users
WHERE age > 25
AND age <= 50
db.users.find(
{ age: { $gt: 25, $lte: 50 } }
)
SELECT *
FROM users
WHERE user_id like "%bc%"
db.users.find( { user_id: /bc/ } )
SELECT *
FROM users
WHERE user_id like "bc%"
db.users.find( { user_id: /^bc/ } )
SELECT *
FROM users
WHERE status = "A"
ORDER BY user_id ASC
db.users.find( { status: "A" } ).sort( { user_id: 1 } )
SELECT *
FROM users
WHERE status = "A"
ORDER BY user_id DESC
db.users.find( { status: "A" } ).sort( { user_id: -1 } )
SELECT COUNT(*)
FROM users
db.users.count()

or

db.users.find().count()
SELECT COUNT(user_id)
FROM users
db.users.count( { user_id: { $exists: true } } )

or

db.users.find( { user_id: { $exists: true } } ).count()
SELECT COUNT(*)
FROM users
WHERE age > 30
db.users.count( { age: { $gt: 30 } } )

or

db.users.find( { age: { $gt: 30 } } ).count()
SELECT DISTINCT(status)
FROM users
db.users.distinct( "status" )
SELECT *
FROM users
LIMIT 1
db.users.findOne()

or

db.users.find().limit(1)
SELECT *
FROM users
LIMIT 5
SKIP 10
db.users.find().limit(5).skip(10)
EXPLAIN SELECT *
FROM users
WHERE status = "A"
db.users.find( { status: "A" } ).explain()

For more information, see db.collection.find()db.collection.distinct(),db.collection.findOne()$ne $and$or$gt$lt$exists$lte$regexlimit(),skip()explain()sort(), and count().

Update Records

The following table presents the various SQL statements related to updating existing records in tables and the corresponding MongoDB statements.

SQL Update Statements MongoDB update() Statements
UPDATE users
SET status = "C"
WHERE age > 25
db.users.update(
{ age: { $gt: 25 } },
{ $set: { status: "C" } },
{ multi: true }
)
UPDATE users
SET age = age + 3
WHERE status = "A"
db.users.update(
{ status: "A" } ,
{ $inc: { age: 3 } },
{ multi: true }
)

For more information, see db.collection.update()$set$inc, and $gt.

Delete Records

The following table presents the various SQL statements related to deleting records from tables and the corresponding MongoDB statements.

SQL Delete Statements MongoDB remove() Statements
DELETE FROM users
WHERE status = "D"
db.users.remove( { status: "D" } )
DELETE FROM users
db.users.remove({})

For more information, see db.collection.remove().

SQL to Aggregation Mapping Chart

The aggregation pipeline allows MongoDB to provide native aggregation capabilities that corresponds to many common data aggregation operations in SQL.

The following table provides an overview of common SQL aggregation terms, functions, and concepts and the corresponding MongoDB aggregation operators:

SQL Terms, Functions, and Concepts MongoDB Aggregation Operators
WHERE $match
GROUP BY $group
HAVING $match
SELECT $project
ORDER BY $sort
LIMIT $limit
SUM() $sum
COUNT() $sum
join No direct corresponding operator; however, the$unwind operator allows for somewhat similar functionality, but with fields embedded within the document.

Examples

The following table presents a quick reference of SQL aggregation statements and the corresponding MongoDB statements. The examples in the table assume the following conditions:

  • The SQL examples assume two tables, orders and order_lineitem that join by theorder_lineitem.order_id and the orders.id columns.

  • The MongoDB examples assume one collection orders that contain documents of the following prototype:

    {
    cust_id: "abc123",
    ord_date: ISODate("2012-11-02T17:04:11.102Z"),
    status: 'A',
    price: 50,
    items: [ { sku: "xxx", qty: 25, price: 1 },
    { sku: "yyy", qty: 25, price: 1 } ]
    }
SQL Example MongoDB Example Description
SELECT COUNT(*) AS count
FROM orders
db.orders.aggregate( [
{
$group: {
_id: null,
count: { $sum: 1 }
}
}
] )
Count all records fromorders
SELECT SUM(price) AS total
FROM orders
db.orders.aggregate( [
{
$group: {
_id: null,
total: { $sum: "$price" }
}
}
] )
Sum theprice field from orders
SELECT cust_id,
SUM(price) AS total
FROM orders
GROUP BY cust_id
db.orders.aggregate( [
{
$group: {
_id: "$cust_id",
total: { $sum: "$price" }
}
}
] )
For each uniquecust_id, sum theprice field.
SELECT cust_id,
SUM(price) AS total
FROM orders
GROUP BY cust_id
ORDER BY total
db.orders.aggregate( [
{
$group: {
_id: "$cust_id",
total: { $sum: "$price" }
}
},
{ $sort: { total: 1 } }
] )
For each uniquecust_id, sum theprice field, results sorted by sum.
SELECT cust_id,
ord_date,
SUM(price) AS total
FROM orders
GROUP BY cust_id,
ord_date
db.orders.aggregate( [
{
$group: {
_id: {
cust_id: "$cust_id",
ord_date: {
month: { $month: "$ord_date" },
day: { $dayOfMonth: "$ord_date" },
year: { $year: "$ord_date"}
}
},
total: { $sum: "$price" }
}
}
] )
For each uniquecust_id,ord_dategrouping, sum the pricefield. Excludes the time portion of the date.
SELECT cust_id,
count(*)
FROM orders
GROUP BY cust_id
HAVING count(*) > 1
db.orders.aggregate( [
{
$group: {
_id: "$cust_id",
count: { $sum: 1 }
}
},
{ $match: { count: { $gt: 1 } } }
] )
For cust_idwith multiple records, return thecust_id and the corresponding record count.
SELECT cust_id,
ord_date,
SUM(price) AS total
FROM orders
GROUP BY cust_id,
ord_date
HAVING total > 250
db.orders.aggregate( [
{
$group: {
_id: {
cust_id: "$cust_id",
ord_date: {
month: { $month: "$ord_date" },
day: { $dayOfMonth: "$ord_date" },
year: { $year: "$ord_date"}
}
},
total: { $sum: "$price" }
}
},
{ $match: { total: { $gt: 250 } } }
] )
For each uniquecust_id,ord_dategrouping, sum the pricefield and return only where the sum is greater than 250. Excludes the time portion of the date.
SELECT cust_id,
SUM(price) as total
FROM orders
WHERE status = 'A'
GROUP BY cust_id
db.orders.aggregate( [
{ $match: { status: 'A' } },
{
$group: {
_id: "$cust_id",
total: { $sum: "$price" }
}
}
] )
For each uniquecust_id with status A, sum the pricefield.
SELECT cust_id,
SUM(price) as total
FROM orders
WHERE status = 'A'
GROUP BY cust_id
HAVING total > 250
db.orders.aggregate( [
{ $match: { status: 'A' } },
{
$group: {
_id: "$cust_id",
total: { $sum: "$price" }
}
},
{ $match: { total: { $gt: 250 } } }
] )
For each uniquecust_id with status A, sum the pricefield and return only where the sum is greater than 250.
SELECT cust_id,
SUM(li.qty) as qty
FROM orders o,
order_lineitem li
WHERE li.order_id = o.id
GROUP BY cust_id
db.orders.aggregate( [
{ $unwind: "$items" },
{
$group: {
_id: "$cust_id",
qty: { $sum: "$items.qty" }
}
}
] )
For each uniquecust_id, sum the corresponding line item qtyfields associated with the orders.
SELECT COUNT(*)
FROM (SELECT cust_id,
ord_date
FROM orders
GROUP BY cust_id,
ord_date)
as DerivedTable
db.orders.aggregate( [
{
$group: {
_id: {
cust_id: "$cust_id",
ord_date: {
month: { $month: "$ord_date" },
day: { $dayOfMonth: "$ord_date" },
year: { $year: "$ord_date"}
}
}
}
},
{
$group: {
_id: null,
count: { $sum: 1 }
}
}
] )

Mongodb 和 普通数据库 各种属性 和语句 的对应的更多相关文章

  1. oracle数据库查询日期sql语句(范例)、向已经建好的表格中添加一列属性并向该列添加数值、删除某一列的数据(一整列)

    先列上我的数据库表格: c_date(Date格式)     date_type(String格式) 2011-01-01                   0 2012-03-07         ...

  2. MySQL、MongoDB、Redis 数据库之间的区别

    NoSQL 的全称是 Not Only SQL,也可以理解非关系型的数据库,是一种新型的革命式的数据库设计方式,不过它不是为了取代传统的关系型数据库而被设计的,它们分别代表了不同的数据库设计思路. M ...

  3. MySQL、MongoDB、Redis 数据库之间的区别与使用(本章迭代更新)

    MySQL.MongoDB.Redis 数据库之间的区别与使用 MySQL.MongoDB.Redis 数据库之间的区别与使用(本章迭代更新) update:2019年2月20日 15:21:19(本 ...

  4. MySQL、MongoDB、Redis数据库Docker镜像制作

    MySQL.MongoDB.Redis数据库Docker镜像制作 在多台主机上进行数据库部署时,如果使用传统的MySQL的交互式的安装方式将会重复很多遍.如果做成镜像,那么我们只需要make once ...

  5. MongoDB和Redis-NoSQL数据库-文档型-内存型

    1NoSQL简述 CAP(Consistency,Availabiity,Partitiontolerance)理论告诉我们,一个分布式系统不可能满足一致性,可用性和分区容错性这三个需求,最多只能同时 ...

  6. MongoDB非关系型数据库开发手册

    一:NoSql数据库 什么是NoSQL? NoSQL,指的是非关系型的数据库.NoSQL有时也称作Not Only SQL的缩写,是对不同于传统的关系型数据库的数据库管理系统的统称. NoSQL用于超 ...

  7. 第12章—使用NoSQL数据库—使用MongoDB+Jpa操作数据库

    使用MongoDB+Jpa操作数据库 SpringData还提供了对多种NoSQL数据库的支持,包括MongoDB;neo4j和redis.他不仅支持自动化的repository,还支持基于模板的数据 ...

  8. 【数据库】 SQL 常用语句之系统语法

    [数据库] SQL 常用语句之系统语法 1. 获取取数据库服务器上所有数据库的名字 SELECT name FROM master.dbo.sysdatabases 2. 获取取数据库服务器上所有非系 ...

  9. MongoDB(三):数据库操作、集合操作

    1. 数据库操作 看完前面的文章,大家应该把环境搭建好了,下面我们就开始学习MongoDB的一些基本操作了. 首先我们要了解的一些要点: MongoDB将数据存储为一个文档,数据结构由键值对(key= ...

随机推荐

  1. DIY Ruby CPU 分析 Part II

    [编者按]作者 Emil Soman,Rubyist,除此之外竟然同时也是艺术家,吉他手,Garden City RubyConf 组织者.本文是 DIY Ruby CPU Profiling 的第二 ...

  2. python语法-[with来自动释放对象]

    python语法-[with来自动释放对象] http://www.cnblogs.com/itech/archive/2011/01/13/1934779.html 一 with python中的w ...

  3. C++11新特性:Lambda函数(匿名函数)

    声明:本文参考了Alex Allain的文章http://www.cprogramming.com/c++11/c++11-lambda-closures.html 加入了自己的理解,不是简单的翻译 ...

  4. POJ2526+简单几何

    题意:给定的这些点是否有一个对称中心. PS:我写得有点啰嗦.. 就是把小的x和大的x进行匹配. #include<stdio.h> #include<algorithm> # ...

  5. Android:常见错误提示

    记录开发中常出现的错误 1.遇到这样的错误时,应该立马想到是书写错误或语法错误,常见为android:name写成了name Attribute is missing the Android name ...

  6. Revit 二次开发 沿弧形路径创建拉伸屋顶

    沿弧形路径创建拉伸屋顶 Revit的API中只能按照直线创建拉伸屋顶,不能按照曲线创建拉伸屋顶.在Revit的界面当中,可以用 构建->内建模型,进行放样创建屋顶.但是没有办法代码内建模型. 可 ...

  7. 从今天起,正式步入cnblogs,向曾经的脚印说声对不起!

    步入这个行业也好多年了,从来没有定居过一个地方. 看过很多前辈们留下的资料,对后者门(其中还有我)留下很多珍贵的东西. 所以,我要向前辈学习,壮大自己,在学习的同时,不要忘记帮助别人. 对曾经我留下的 ...

  8. NFC(5)编写NFC程序的基本步骤

    1,设置权限 <uses-permission android:name="android.permission.NFC" /> 2,限制Android版本 <u ...

  9. 获取html上元素的真正坐标

    使用HTML元素的style.left,style.top,style.width,style.height以及width,height属性,都不能获得元素的真正位置与大小,这些属性取出来的都是原来的 ...

  10. 【ZOJ】2112 Dynamic Rankings

    树状数组套主席树模板题目. /* 2112 */ #include <iostream> #include <sstream> #include <string> ...