一、查询所有列
MongoDB查询使用find()。
1.无条件查询
db.sam.find()
等效于SQL:select * from sam;
2.等值条件
db.sam.find({name:“Sam”})
等效于SQL:select * from sam where name=‘Sam’;
3.in条件
db.sam.find({name:{KaTeX parse error: Expected 'EOF', got '}' at position 17: …n:["Sam","Tom"]}̲}) 等效于SQL:selec…lt:25}})
等效于SQL:select * from sam where gender=‘Y’ and age<25;
5.or条件
db.sam.find({KaTeX parse error: Expected '}', got 'EOF' at end of input: …e:"sam"},{age:{gt:18}}]})
等效于SQL:select * from sam where name=‘Sam’ or age > 18;
6.and 和 or 混合
db.sam.find({name:“Sam”},$or:[{gender:“Y”},{age:25}])
等效于SQL:select * from sam where name=‘Sam’ or (gender=‘Y’ and age=25);
二、查询嵌套列
例如以下一个文档:
{name:"Sam",age:25,body:{h:175,w:68},luky_number:[1,3,6]}
1.根据body全匹配查询
db.sam.find({body:{h:175,w:68}})
2.根据body的h来匹配文档,查找h>170的文档
db.sam.find({“body.h”:{$gt:170}})
三、查询数组列
例如以下一个文档:
db.sam.insert({name:"Sam",age:25,interest:["music","film","game"]})
1.根据interest全匹配查找,只有完全匹配的文档才返回
db.sam.find({interest:[“film”,“basketball”]})
2.查找insterest包含某些元素的文档,只要数组列包含指定元素即可
db.sam.find({interest:{KaTeX parse error: Expected 'EOF', got '}' at position 20: …["film","read"]}̲}) 3.查找interest…gt:4,KaTeX parse error: Expected 'EOF', got '}' at position 5: lt:5}̲}) 由于1满足lt:5,而6满足KaTeX parse error: Expected '}', got 'EOF' at end of input: …({luky_number:{elemMatch:{
g
t
:
4
,
gt:4,
gt:4,lt:5}}})
这个命令需要luky_number中某一个元素同时满足
g
t
:
4
,
gt:4,
gt:4,lt:6,所以实例数据不是满足条件的文档
三、指定返回列
如
db.sam.find({name:“Sam”})
等效于SQL:select * from sam where name=‘Sam’;
而
db.sam.find({name:“Sam”},{name:1,age:1})
等效于SQL:select _id,name,age from sam where name=‘Sam’;
而
db.sam.find({name:“Sam”},{name:1,age:1,_id:0})
等效于SQL:select name,age from sam where name=‘Sam’;
或者返回结果排除name列:
db.sam.find({name:“Sam”},{name:0})
四、查询不包含某个列的文档
如不返回没有age列的文档:
db.sam.find({age:{$exists:false}})