You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB嵌套布尔字段查询:如何返回对应布尔值结果

解决方案:根据嵌套字段返回布尔结果

针对你的需求,不需要用到$lookup(关联集合用)或$where(性能较差的JS查询),直接通过聚合管道的操作符就能提取嵌套字段并转换为布尔值。以下是具体实现:

场景1:data数组仅包含单个元素(匹配你的示例结构)

修改聚合查询,提取嵌套字段并转换为布尔类型:

db = db.getSiblingDB("test-db");
hosts = db.getCollection("test-collection")
db.hosts.aggregate([
    // 保留原有的IP过滤条件
    {$match: {"ip_str": {$in: ["52.217.105.116"]}}},
    // 添加字段,将字符串形式的expired转换为布尔值
    {$addFields: {
        "is_expired": {$toBool: {$arrayElemAt: ["$data.ssl.cert.expired", 0]}}
    }},
    // 可选:只返回需要的字段,剔除多余数据
    {$project: {
        _id: 0,
        ip_str: 1,
        is_expired: 1
    }}
]);

关键操作解释:

  • $arrayElemAt: ["$data.ssl.cert.expired", 0]:从data数组中取出第一个元素的ssl.cert.expired字符串值(因为$data.ssl.cert.expired会返回一个由数组内所有元素对应字段组成的新数组)
  • $toBool:自动将字符串"True"/"False"转换为对应的布尔类型(大小写不敏感,"false"或"FALSE"也能正确转换)

执行后返回结果类似:

{ "ip_str" : "52.217.105.116", "is_expired" : false }

场景2:data数组包含多个元素,需批量判断

如果data里有多个SSL证书,可根据需求选择不同逻辑:

  • 判断是否存在过期证书:
    {$addFields: {
        "has_expired_cert": {
            $anyElementTrue: {
                $map: {
                    input: "$data",
                    as: "item",
                    in: {$toBool: "$$item.ssl.cert.expired"}
                }
            }
        }
    }}
    
  • 判断所有证书是否都过期:
    {$addFields: {
        "all_certs_expired": {
            $allElementsTrue: {
                $map: {
                    input: "$data",
                    as: "item",
                    in: {$toBool: "$$item.ssl.cert.expired"}
                }
            }
        }
    }}
    

内容的提问来源于stack exchange,提问作者user19479943

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 17:06:49