Wednesday, August 13, 2014

M101J: MongoDB for Java Developers - Homework 2.1

Step 1:
Download Grades.js
 
Step 2:
Load grade.js using mongo import
 
mongoimport -d students -c grades < grades.js
 
Step 3:
use students
db.grades.count() 

Count Should be 800

Step 4:
Question? 
Find all exam scores greater than or equal to 65 
and sort those scores from lowest to highest. 
 
Understanding Question:
1) it says that we need to find score greater than or equal to 65.
so we will use $gte so our query criteria will be 
{"score":{"$gte":65}}
 
2) then it says to sort the score from lowest to highest.
for this we will use sort filter  and it is query criteria will be 
{"score":1}.

so our query will be 
 db.grades.find({"score":{"$gte":65.0}}).sort({"score":1})
 
Note: to sort in ascending order use  {"score":1}
to sort in descending order use  {"score":-1}
 
first document in the result you will find the answer 

3) optional : you can limit the number of rows, you will get only 1 document
by executing final query. so that you dont have to scroll. 
 
 
Final Query: 
 db.grades.find({"score":{"$gte":65.0}}).sort({"score":1}).limit(1).pretty();

No comments:

Post a Comment