发布于

MongoDB 高级查询(二):对内嵌对象中字段的比较

在上一篇文章中,我们讨论了使用 $where,但这种方法有一个严重的缺点:它消耗了太多的性能,通常因为查询执行缓慢而不推荐使用。

言归正传!

需要查询的表格

{
    "health": {
        "diastolicpressure": 95,
        "systolicpressure": 155,
        "waist": 72
    },
    "calculation": {
        "target": {
            "systolicpressure": 138,
            "diastolicpressure": 80,
            "weight": 67.375
        }
    }
}

{
    "health": {
        "diastolicpressure": 79,
        "systolicpressure": 120,
        "waist": 50
    },
    "calculation": {
        "target": {
            "systolicpressure": 138,
            "diastolicpressure": 80,
            "weight": 67.375
        }
    }
}

查询需求

找出表格中 health.diastolicpressure 大于 calculation.target.diastolicpressure 的数据。

Shell 中单个条件比较查询实现

db.members.aggregate([
    {
        $match: {
            sid: "aaa-PJx"   // 筛选 -- 先匹配这个,满足这个的才进行下面的匹配
        }
    },
    {
        $redact: {
            "$cond": [
                {
                    "$gt": ["$health.systolicpressure", "$calculation.target.systolicpressure"]
                },
                "$$KEEP", "$$PRUNE"
            ]
        }
    }
]).pretty()

Shell 中多个条件比较查询实现

db.members.aggregate([
    {
        $match: {
            sid: "aaa-PJx"
        }
    },
    {
        $redact: {
            "$cond": [
                {
                    "$and": [
                        {
                            "$gt": ["$health.systolicpressure", "$calculation.target.systolicpressure"]
                        },
                        {
                            "$gt": ["$health.diastolicpressure", "$calculation.target.diastolicpressure"]
                        }
                    ]
                },
                "$$KEEP", "$$PRUNE"
            ]
        }
    }
]).pretty()