MongoDB 文档投影

find 第2个参数用于指定返回哪些字段、不返回哪些字段。1 返回,0不返回

> db.accounts.find({},{name:1,_id:0})
{ "name" : "alice2" }
{ "name" : "charlie" }
{ "name" : "david" }
{ "name" : "charlie" }
{ "name" : "david" }

如果字段筛选不含主键字段,则不能混合使用包含与不包含

> db.accounts.find({},{name:1,balance:0}).limit(5)
Error: error: {
 "ok" : 0,
 "errmsg" : "Projection cannot have a mix of inclusion and exclusion.",
 "code" : 2,
 "codeName" : "BadValue"
}

如果字段是数组类型,使用 slice 化繁为简

> db.accounts.find({name:'alice2','contact':{$exists:true}},{_id:0,name:1,contact:1})
{ "name" : "alice2", "contact" : [ 13611111111, "Guangzhou" ] }
{ "name" : "alice2", "contact" : [ [ 13611111111, 13622222222 ], "Guangzhou" ] }
# $slice 为 1 只返回 contact 数组的第 1 个元素,为 -1 返回倒数第1个元素 ,为数组返回元素列表
> db.accounts.find({name:'alice2','contact':{$exists:true}},{_id:0,name:1,contact:{$slice:1}})
{ "name" : "alice2", "contact" : [ 13611111111 ] }
{ "name" : "alice2", "contact" : [ [ 13611111111, 13622222222 ] ] }

如果字段是数组类型,使用 elemMatch 化繁为简,elemMatch 只会返回符合条件的第 1 个元素

> db.accounts.find({name:'alice2','contact':{$exists:true}},{_id:0,name:1,contact:{$elemMatch:{$lt:13622222222}}})
{ "name" : "alice2", "contact" : [ 13611111111 ] }
{ "name" : "alice2" }

如果字段是数组类型,使用 $ 化繁为简,会借用find方法中第一个参数设定好的规则,同时只会返回符合条件的第 1 个元素

> db.accounts.find({name:'alice2','contact':{$exists:true,$lt:13622222222}},{_id:0,name:1,"contact":1})
{ "name" : "alice2", "contact" : [ 13611111111, "Guangzhou" ] }
> db.accounts.find({name:'alice2','contact':{$exists:true,$lt:13622222222}},{_id:0,name:1,"contact.$":1})
{ "name" : "alice2", "contact" : [ 13611111111 ] }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值