1、查詢所有記錄
復制代碼代碼如下:
db.userInfo.find();
相當於:select* from userInfo;
默認每頁顯示20條記錄,當顯示不下的情況下,可以用it迭代命令查詢下一頁數據。注意:鍵入it命令不能帶“;”但是你可以設置每頁顯示數據的大小,用DBQuery.shellBatchSize= 50;這樣每頁就顯示50條記錄了。
2、查詢去掉後的當前聚集集合中的某列的重復數據
復制代碼代碼如下:
db.userInfo.distinct("name");
會過濾掉name中的相同數據
相當於:select distict name from userInfo;3、查詢age = 22的記錄
復制代碼代碼如下:
db.userInfo.find({"age": 22});
相當於: select * from userInfo where age = 22;
復制代碼代碼如下:
db.userInfo.find({age: {$gt: 22}});
相當於:select * from userInfo where age >22;
復制代碼代碼如下:
db.userInfo.find({age: {$lt: 22}});
相當於:select * from userInfo where age <22;
db.userInfo.find({age: {$gte: 25}});
相當於:select * from userInfo where age >= 25;
db.userInfo.find({age: {$lte: 25}});
8、查詢age >= 23 並且 age <= 26
復制代碼代碼如下:db.userInfo.find({age: {$gte: 23, $lte: 26}});
db.userInfo.find({name: /mongo/});
//相當於%%
select * from userInfo where name like ‘%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;
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});
db.userInfo.find({name: 'zhangsan', age: 22});相當於:select * from userInfo where name = ‘zhangsan' and age = ‘22';
15、查詢前5條數據
復制代碼代碼如下:db.userInfo.find().limit(5);相當於:select top 5 * from userInfo;
16、查詢10條以後的數據
復制代碼代碼如下:db.userInfo.find().skip(10);
相當於:
select * from userInfo where id not in (
select top 10 * from userInfo17、查詢在5-10之間的數據
復制代碼代碼如下:db.userInfo.find().limit(10).skip(5);limit是限制顯示的數量,skip是跳過的數量。
18、or與 查詢
復制代碼代碼如下:db.userInfo.find({$or: [{age: 22}, {age: 25}]});相當於:select * from userInfo where age = 22 or age = 25;
19、查詢第一條數據
復制代碼代碼如下:db.userInfo.findOne();
相當於:
select top 1 * from userInfo;
db.userInfo.find().limit(1);
db.userInfo.find({age: {$gte: 25}}).count();
相當於:select count(*) from userInfo where age >= 20;
db.userInfo.find({sex: {$exists: true}}).count();相當於:select count(sex) from userInfo;