• 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 ] }
    
  • 相关阅读:
    python3.5以上版本,typing模块提高代码健壮性
    psutil模块使用
    不懂前后端分离?这篇就够了
    k8s krew 插件管理工具
    metrics-server 安装问题解决
    k8s dashboard 解决secret自建证书导致浏览器访问限制
    创建私有 Gems 源
    windows10 使用WSL(ubuntu系统,xshell连接)
    将 Oracle VirtualBox 中运行的虚拟机导入 VMware Fusion、Workstation 或 Player
    conflunce安装配置
  • 原文地址:https://www.cnblogs.com/zy108830/p/12639628.html
Copyright © 2020-2023  润新知