zoukankan      html  css  js  c++  java
  • 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 ] }
    
  • 相关阅读:
    怎么往mac中finder个人收藏里添加文件夹
    UIView 动画
    添加.pch文件
    声明属性的关键字
    创建app前的环境配置/AppIcon/启动图片
    修改动画的旋转支点
    实现自定义xib和storyboard的加载,
    Quartz2D绘图 及实例:下载进度
    帧动画
    在职研究生第一单元第二单元第三单元第四单元是什么?
  • 原文地址:https://www.cnblogs.com/zy108830/p/12639628.html
Copyright © 2011-2022 走看看