- Create a new database
- Query data multiple ways
By the end of this Unit, you should understand:
- How to organize data in collections
- Mongo collection/document structure
By the end of this Unit, you should be able to
- Navigate databases and collections using the Mongo Shell
- Query collections for documents based on various criteria
Let's revisit some sample data. Logging back into our cluster with the
Mongo Shell, select the sample_training
database. You'll see several
collections with show collections
. Let's use the grades
collection for
some practice.
The find()
method takes a JS-like object as an argument. In it, we can
provide keys and values to match on. For example, after
db.grades.findOne()
reveals the structure of our documents, we could
try:
db.grades.find({student_id: 0})
This will return grades for student 0. We could add another key/value pair
in that object for a specific class_id
to match on grades from only that
class.
Maybe we don't need all the fields that are getting returned. We can pass
a second argument to .find()
that will tell Mongo which fields to
return. In this case, the object keys will be the fields we want, and
a 1 to confirm we want to include them.
db.grades.find({student_id: 0},{scores: 1,class_id: 1}).pretty()
Mongo has a host of query
operators
you can use in your find()
argument. Say you wanted all student_id
s
under 10:
db.grades.find({student_id: {$lt: 10}}).pretty()
Note the use of an object to contain the query operator(s).
We can also access the values of arrays within our documents. Say we wanted to get all records containing grades above 90:
db.grades.find({"scores.score":{$gt: 90}}, {scores: 1, class_id:
1, student_id: 1}).pretty()
With that, you're fairly well-equipped to query data in complex ways.
Using any of the sample databases, create 3 queries of the data using either scalar values or query operators. Post the queries and 1 resulting document to the discussion forum.