0
点赞
收藏
分享

微信扫一扫

MongoDB 聚合管道中使用逻辑表达式运算符

月孛星君 2023-04-27 阅读 74

逻辑表达式运算符主要用于实现表达式之间的逻辑运算,主要包含了与、或、非等逻辑操作。

一、准备工作

初始化学生成绩

db.scores.insertMany([
    { "_id" : 1, "name" : "张三", "eng" : 80, "math" : 70 },
    { "_id" : 2, "name" : "李四", "eng" : 60, "math" : 90 },
    { "_id" : 3, "name" : "王五", "eng" : 90, "math" : 50 }
])

二、与($and)

语法:{ $and: [ <expression1>, <expression2>, ... ] }

所有的表达式的结果都为true,最后的返回结果才为true,否则返回false

例子:查找英语成绩和数学成绩都及格的学生

db.scores.aggregate([
    {
        $match: {
            $expr: {
                $and: [
                    { "$gte": [ "$eng", 60 ] }, 
                    { "$gte": [ "$math", 60 ] }
                ]
            }
        }
    }
])

等效于:

db.scores.aggregate([
    {
        $match: {
            "eng": { $gte: 60 },
            "math": { $gte: 60 }
        }
    }
])

等效于:

db.scores.aggregate([
    {
        $match: {
            $and: [
                { "eng": { $gte: 60 } },
                { "math": { $gte: 60 } }
            ]
        }
    }
])

聚合查询的结果如下:

{ "_id" : 1, "name" : "张三", "eng" : 80, "math" : 70 }
{ "_id" : 2, "name" : "李四", "eng" : 60, "math" : 90 }

三、或($or)

语法:{ $or: [ <expression1>, <expression2>, ... ] }

只要有一个表达式的结果为true,最后的返回结果就为true,否则返回false

例子:查找英语成绩或者数学成绩超过80的学生

db.scores.aggregate([
    {
        $match: {
            $expr: {
                $or: [
                    { $gt: [ "$eng", 80 ] },
                    { $gt: [ "$math", 80 ] }
                ]
            }
        }
    }
])

等效于:

db.scores.aggregate([
    {
        $match: {
            $or: [
                { "eng": { $gt: 80 } },
                { "math": { $gt: 80 } }
            ]
        }
    }
])

聚合查询的结果如下:

{ "_id" : 2, "name" : "李四", "eng" : 60, "math" : 90 }
{ "_id" : 3, "name" : "王五", "eng" : 90, "math" : 50 }

四、非($not)

语法:{ $not: [ <expression> ] }

如果表达式的结果为true,则返回false

如果表达式的结果为false,则返回true

例子:查找英语成绩不及格的学生

db.scores.aggregate([
    {
        $match: {
            $expr: { 
                $not: { $gte: [ "$math", 60 ] }
            }
        }
    }
])

等效于:

db.scores.aggregate([
    {
        $match: {
            $expr: { 
                $lt: [ "$math", 60 ]
            }
        }
    }
])

等效于:

db.scores.aggregate([
    {
        $match: {
            "math": { $lt: 60 }
        }
    }
])

聚合查询的结果如下:

{ "_id" : 3, "name" : "王五", "eng" : 90, "math" : 50 }
举报

相关推荐

0 条评论