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 ] }

猜你喜欢

转载自www.cnblogs.com/zy108830/p/12639628.html