MongoDB基礎操作2

四、查詢操作

1、查詢所有記錄

db.userInfo.find();

相當于:select* from userInfo;

2、查詢去掉后的當前聚集集合中的某列的重復數據

db.userInfo.distinct("name");會過濾掉name中的相同數據

相當于:select disttince name from userInfo;

3、查詢age = 22的記錄

db.userInfo.find({"age": 22});

相當于: select * from userInfo where age = 22;

4、查詢age > 22的記錄

db.userInfo.find({age: {$gt: 22}});

相當于:select * from userInfo where age >22;

5、查詢age < 22的記錄

db.userInfo.find({age: {$lt: 22}});

相當于:select * from userInfo where age <22;

6、查詢age >= 25的記錄

db.userInfo.find({age: {$gte: 25}});

相當于:select * from userInfo where age >= 25;

7、查詢age <= 25的記錄

db.userInfo.find({age: {$lte: 25}});

相當于:select * from userInfo where age <= 25;

8、查詢age >= 23 并且 age <= 26

db.userInfo.find({age: {$gte: 23, $lte: 26}});

相當于:select * from userInfo where age >=23 and age <= 26;

9、查詢name中包含 mongo的數據

db.userInfo.find({name: /mongo/});

相當于:select * from userInfo where name like ‘%mongo%';

10、查詢name中以mongo開頭的

db.userInfo.find({name: /^mongo/});

相當于:select * from userInfo where name like ‘mongo%';

11、查詢指定列name、age數據

db.userInfo.find({}, {name: 1, age: 1});

相當于:select name, age from userInfo;

當然name也可以用true或false,當用ture的情況下河name:1效果一樣,如果用false就是排除name,顯示name以外的列信息。

12、查詢指定列name、age數據, age > 25

db.userInfo.find({age: {$gt: 25}}, {name: 1, age: 1});

相當于:select name, age from userInfo where age >25;

13、按照年齡排序

升序:db.userInfo.find().sort({age: 1});

降序:db.userInfo.find().sort({age: -1});

14、查詢前5條數據

db.userInfo.find().limit(5);

相當于:select * from (select * from userInfo) where rownum < 6;//oracle

select * from userInfo limit 5;//mysql

15、查詢10條以后的數據

db.userInfo.find().skip(10);

相當于:select * from userInfo where id not in (select id from (select * from userInfo) where? and rownum < 11);

16、查詢在5-10之間的數據

db.userInfo.find().limit(10).skip(5);

可用于分頁,limit是pageSize,skip是第幾頁*pageSize

17、or與 查詢

db.userInfo.find({$or: [{age: 22}, {age: 25}]});

相當于:select * from userInfo where age = 22 or age = 25;

18、查詢第一條數據

db.userInfo.findOne();

db.userInfo.find().limit(1);

相當于:select * from (select * from userInfo) where? and rownum < 2

19、查詢某個結果集的記錄條數

db.userInfo.find({age: {$gte: 25}}).count();

相當于:select count(*) from userInfo where age >= 20;

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • 最近在學習MongoDB,整理梳理一下各種命令,怕以后忘記,以后可以自己查閱! 常用的方法: 示例: 文件導出至J...
    Kalvin_Tse閱讀 858評論 3 3
  • 一、數據庫常用命令1、Help查看命令提示 復制代碼 代碼如下: helpdb.help();db.yourCol...
    字伯約閱讀 433評論 0 0
  • 成功啟動MongoDB后,再打開一個命令行窗口輸入mongo,就可以進行數據庫的一些操作。輸入help可以看到基本...
    精氣神貫通閱讀 506評論 0 0
  • 成功啟動MongoDB后,再打開一個命令行窗口輸入mongo,就可以進行數據庫的一些操作。 輸入help可以看到基...
    你本來就很牛閱讀 28,789評論 0 3
  • MongoDB是一個基于分布式文件存儲的數據庫。由C++語言編寫。旨在為WEB應用提供可擴展的高性能數據存儲解決方...
    入戲半分笑閱讀 438評論 0 2

友情鏈接更多精彩內容