We have introduced before using comparison selectors, logical selectors, element selectors, and array selectors to query documents. If you need further information, you can refer to:
Comparison selectors and logical selectors are used in MongoDB query documents https://blog.csdn.net/m1729339749/article/details/129965699 Element selectors and array selectors are used in MongoDB query documents https://blog.csdn.net /m1729339749/article/details/129971708 In this article, we introduce the use of $expr and $where selectors to query documents:
1. Preparation
Initialize course grade data
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 }
])
2. Use aggregation expressions to query documents ($expr)
grammar:
{ $expr: { <expression> } }
Allows querying documents using aggregate expressions in query statements
If you don't know much about aggregation expressions , you can refer to:
Example: Filtering Students' Mathematics Course Grades
db.subjectScores.find({
$expr: { $eq: [ "$subject", "math" ] }
})
Equivalent to:
db.subjectScores.find({
"subject": "math"
})
Equivalent to:
db.subjectScores.find({
"subject": {
$eq: "math"
}
})
The result of the query is as follows:
{ "_id" : 4, "name" : "张三", "subject" : "math", "score" : 70 }
{ "_id" : 5, "name" : "李四", "subject" : "math", "score" : 90 }
{ "_id" : 6, "name" : "王五", "subject" : "math", "score" : 50 }
3. Use the js function to query the document ($where)
grammar:
{ $where: <JavaScript Code> }
Query documents using js functions
Example: Filtering Students' Mathematics Course Grades
db.subjectScores.find({
$where: function() {
return this.subject === "math";
}
})
Alternatively, we can use the aggregate expression operator $function in $expr instead of $where :
db.subjectScores.find({
$expr: {
$function: {
body: function(s) {
return s === "math";
},
args: [ "$subject" ],
lang: "js"
}
}
})
If you don't know much about $function , you can refer to:
The result of using the custom aggregate expression operator ($function) https://blog.csdn.net/m1729339749/article/details/130597563 query in the MongoDB aggregation pipeline is as follows:
{ "_id" : 4, "name" : "张三", "subject" : "math", "score" : 70 }
{ "_id" : 5, "name" : "李四", "subject" : "math", "score" : 90 }
{ "_id" : 6, "name" : "王五", "subject" : "math", "score" : 50 }