MongoDB 和 MySQL 是两种常见的关系型数据库管理系统(RDBMS)和文档型数据库,它们在SQL语句的语法和功能上有所不同。在这篇速成教程中,我们将探讨MongoDB中常用的SQL等效查询语句以及它们与MySQL的区别。 1. 插入数据: - MySQL: `INSERT INTO users (a, b) VALUES (3, 5);` - MongoDB: `db.users.insert({ a: 3, b: 5 });` 2. 查询数据: - MySQL: `SELECT a, b FROM users;`(获取所有字段) - MongoDB: `db.users.find();`(默认查询所有文档,无筛选条件) 3. 精确匹配查询: - MySQL: `SELECT * FROM users WHERE age = 33;` - MongoDB: `db.users.find({ age: 33 });` 或 `db.users.find({ 'age': 33 })`(注意键值对的引号处理) 4. 选择部分字段: - MySQL: `SELECT a, b FROM users WHERE age = 33;` - MongoDB: `db.users.find({ age: 33 }, { a: 1, b: 1 });` 5. 排序: - MySQL: `SELECT * FROM users WHERE age > 33 ORDER BY name;` - MongoDB: `db.users.find({ age: { $gt: 33 } }).sort({ name: 1 });` (升序,1表示正向排序) 6. 条件比较: - MySQL: `SELECT * FROM users WHERE age != 33;` - MongoDB: `db.users.find({ age: { $ne: 33 } });` - 正则表达式匹配:`db.users.find({ name: { $regex: /Joe/ } });`,其中`/Joe/`用于模糊搜索包含"Joe"的姓名。 7. 多条件查询: - MySQL: `SELECT * FROM users WHERE age > 33 AND age <= 40;` - MongoDB: `db.users.find({'age': { $gt: 33, $lte: 40 }});` 8. 分页查询: - MySQL: `SELECT * FROM users LIMIT 10 OFFSET 20;` - MongoDB: `db.users.find().limit(10).skip(20);` 9. OR 条件查询: - MySQL: `SELECT * FROM users WHERE a = 1 OR b = 2;` - MongoDB: `db.users.find({ $or: [{ a: 1 }, { b: 2 }] });` 10. 单个文档查找: - MySQL: `SELECT order_id FROM orders JOIN order_line_items ON li.order_id = o.order_id WHERE li.order_id = ?;` - MongoDB: `db.orders.findOne({ 'order_line_items.order_id': ? });`(假设order_id是嵌套文档中的属性) 总结起来,MongoDB的查询语法更偏向于文档操作,使用JSON风格的键值对表示查询条件,而MySQL则依赖标准的SQL语句。在处理复杂的数据结构和灵活的查询条件时,MongoDB提供了更大的灵活性,但SQL查询对于熟悉的关系型数据库用户更为直观。了解这些差异可以帮助开发者根据具体需求选择合适的数据库系统。
db.users.insert({a:3,b:5})
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:{$ne: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/})
下载后可阅读完整内容,剩余3页未读,立即下载
- 粉丝: 0
- 资源: 8
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
最新资源
- C++多态实现机制详解:虚函数与早期绑定
- Java多线程与异常处理详解
- 校园导游系统:无向图实现最短路径探索
- SQL2005彻底删除指南:避免重装失败
- GTD时间管理法:提升效率与组织生活的关键
- Python进制转换全攻略:从10进制到16进制
- 商丘物流业区位优势探究:发展战略与机遇
- C语言实训:简单计算器程序设计
- Oracle SQL命令大全:用户管理、权限操作与查询
- Struts2配置详解与示例
- C#编程规范与最佳实践
- C语言面试常见问题解析
- 超声波测距技术详解:电路与程序设计
- 反激开关电源设计:UC3844与TL431优化稳压
- Cisco路由器配置全攻略
- SQLServer 2005 CTE递归教程:创建员工层级结构