MongoDB CURD之READ

本文深入讲解MongoDB查询操作,包括无条件查询、等值条件、in条件、and条件、or条件及混合使用,同时覆盖查询嵌套列、数组列的方法,并介绍如何指定返回列和查询不包含特定列的文档。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、查询所有列
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}})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值