MongoDB 查询文档中使用$expr、$where选择器

之前我们介绍过使用比较选择器、逻辑选择器、元素选择器、数组选择器查询文档,如果您需要进一步了解,可以参考:

MongoDB 查询文档中使用比较选择器、逻辑选择器icon-default.png?t=N3I4https://blog.csdn.net/m1729339749/article/details/129965699MongoDB 查询文档中使用元素选择器、数组选择器icon-default.png?t=N3I4https://blog.csdn.net/m1729339749/article/details/129971708本篇,我们介绍使用$expr、$where选择器查询文档:

一、准备工作

初始化课程成绩数据

db.subjectScores.insertMany([
    { "_id": 1, "name": "张三", "subject": "eng", "score": 80 },
    { "_id": 2, "name": "李四", "subject": "eng", "score": 60 },
    { "_id": 3, "name": "王五", "subject": "eng", "score": 90 },
    { "_id": 4, "name": "张三", "subject": "math", "score": 70 },
    { "_id": 5, "name": "李四", "subject": "math", "score": 90 },
    { "_id": 6, "name": "王五", "subject": "math", "score": 50 },
    { "_id": 7, "name": "张三", "subject": "physics", "score": 80 },
    { "_id": 8, "name": "李四", "subject": "physics", "score": 60 },
    { "_id": 9, "name": "王五", "subject": "physics", "score": 70 }
])

二、使用聚合表达式查询文档($expr)

语法:

{ $expr: { <expression> } }

在查询语句中允许使用聚合表达式查询文档

如果您对聚合表达式不太了解,可以参考:

MongoDB 聚合管道的使用及聚合表达式的介绍icon-default.png?t=N3I4https://blog.csdn.net/m1729339749/article/details/130034020

例子:筛选学生的数学课程成绩

db.subjectScores.find({
    $expr: { $eq: [ "$subject", "math" ] }
})

等效于:

db.subjectScores.find({
    "subject": "math"
})

等效于:

db.subjectScores.find({
    "subject": {
        $eq: "math"
    }
})

查询的结果如下:

{ "_id" : 4, "name" : "张三", "subject" : "math", "score" : 70 }
{ "_id" : 5, "name" : "李四", "subject" : "math", "score" : 90 }
{ "_id" : 6, "name" : "王五", "subject" : "math", "score" : 50 }

三、使用js函数查询文档($where)

语法:

{ $where: <JavaScript Code> }

使用js函数查询文档

例子:筛选学生的数学课程成绩

db.subjectScores.find({
    $where: function() {
        return this.subject === "math";
    }
})

另外,我们可以在$expr中使用聚合表达式运算符$function来替代$where

db.subjectScores.find({
    $expr: {
        $function: {
            body: function(s) {
                return s === "math";
            },
            args: [ "$subject" ],
            lang: "js"
        }
    }
})

如果您对$function不太了解,可以参考:

MongoDB 聚合管道中使用自定义聚合表达式运算符($function)icon-default.png?t=N3I4https://blog.csdn.net/m1729339749/article/details/130597563查询的结果如下:

{ "_id" : 4, "name" : "张三", "subject" : "math", "score" : 70 }
{ "_id" : 5, "name" : "李四", "subject" : "math", "score" : 90 }
{ "_id" : 6, "name" : "王五", "subject" : "math", "score" : 50 }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值