之前我们介绍过使用比较选择器、逻辑选择器、元素选择器、数组选择器查询文档,如果您需要进一步了解,可以参考:
MongoDB 查询文档中使用比较选择器、逻辑选择器https://blog.csdn.net/m1729339749/article/details/129965699MongoDB 查询文档中使用元素选择器、数组选择器https://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 聚合管道的使用及聚合表达式的介绍https://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)https://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 }