MongoDB常用查询SQL

190 阅读1分钟

公司前段时间做项目使用到了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}});lt(<) lt(<) lte(<=) gt(>) gt(>) 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);