公司前段时间做项目使用到了mongoDB,对里面的SQL写法不是很了解,在此做一个记录
| 查询场景 | sql语句 | mongo语句 | 备注 |
|---|---|---|---|
| 查询所有数据 | select * from collection; | db.getCollection('collection').find(); | |
| 查询所有数据,显示指定字段 | select column1,column2 from collection; | db.getCollection('collection').find({},{"column1":1,"column2":1}); | _id字段会默认显示 |
| 查询所有数据,显示指定字段(不显示_id) | select column1,column2 from collection; | db.getCollection('collection').find({},{"column1":1,"column2":1,"_id":0}); | "_id":0,强制不显示_id字段 |
| 带条件查询数据 | select * from collection where column1 = '1'; | db.getCollection('collection').find({"column1":"1"}); | |
| 带多个条件查询数据 | select * from collection where column1 = '1' and column2 = '2'; | db.getCollection('collection').find({$and:[{"column1":"1"},{"column2":"2"}]}); | |
| 带多个条件查询数据 | select * from collection where age >= '10' and age = '20'; | db.getCollection('collection').find({"age" : {"$gte" : 10, "$lte" : 20}}); | lte(<=) gte(>=) $ne(!=) |
| 排序 | select * from collection where column1 = '1' order by column1; | db.getCollection('collection').find({"column1":"1"}).sort({"column1":1}); | 1:正序,-1:倒序 |
| 查询前N条数据 | select * from collection where column1 = '1' order by column1 limit 3; | db.getCollection('collection').find({"column1":"1"}).sort({"column1":1}).limit(3); |