MongoDB Evaluation Query operator - $where
Description
The MongoDB $where operator is used to match documents that satisfy a JavaScript expression. A string containing a JavaScript expression or a JavaScript function can be pass using the $where operator. The JavaScript expression or function may be referred as this or obj.
Our database name is 'myinfo' and our collection name is 'table3'. Here, is the collection bellow.
Sample collection "table3"
{
"_id" : ObjectId("52873b364038253faa4bbc0e"),
"student_id" : "STU002",
"sem" : "sem1",
"english" : "A",
"maths" : "A+",
"science" : "A"
}
{
"_id" : ObjectId("52873b5d4038253faa4bbc0f"),
"student_id" : "STU001",
"sem" : "sem1",
"english" : "A+",
"maths" : "A+",
"science" : "A"
}
{
"_id" : ObjectId("52873b7e4038253faa4bbc10"),
"student_id" : "STU003",
"sem" : "sem1",
"english" : "A+",
"maths" : "A",
"science" : "A+"
}
Example of MongoDB Evaluation Query operator - $where
If we want to select all documents from the collection "table3" which satisfying the condition -
The grade of english must be same as science
the following mongodb command can be used :
>db.table3.find( { $where: function() { return (this.english == this.science) }}).pretty();
N.B. find() method displays the documents in a non structured format but to display the results in a formatted way, the pretty() method can be used.
Output:
{ "_id" : ObjectId("52873b364038253faa4bbc0e"), "student_id" : "STU002", "sem" : "sem1", "english" : "A", "maths" : "A+", "science" : "A" } { "_id" : ObjectId("52873b7e4038253faa4bbc10"), "student_id" : "STU003", "sem" : "sem1", "english" : "A+", "maths" : "A", "science" : "A+" }
If we want to get the above output the other mongodb statements can be written as below -
>db.table3.find( { $where: function() { return (obj.english == obj.science)}}).pretty();
>db.table3.find( "this.english == this.science").pretty();
Previous:
$regex
Next:
Query Operator Array $all
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/mongodb/mongodb-where-operators.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics