Skip to content

Instantly share code, notes, and snippets.

@theperfectfuel
Last active June 18, 2019 21:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theperfectfuel/7fdd6294c64d932082b44fdbc6d3cc6d to your computer and use it in GitHub Desktop.
Save theperfectfuel/7fdd6294c64d932082b44fdbc6d3cc6d to your computer and use it in GitHub Desktop.
Unit 2 of the everLive MongoDB course curriculum

MongoDB Course Curriculum

Unit 2: Documents and Collections

Goals for this Unit

  • Create a new database
  • Query data multiple ways

Theory and Knowledge

By the end of this Unit, you should understand:

  • How to organize data in collections
  • Mongo collection/document structure

Skills

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

Advanced Queries

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.

Find by Criteria

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.

Projections

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()

Query Operators

Mongo has a host of query operators you can use in your find() argument. Say you wanted all student_ids under 10:

db.grades.find({student_id: {$lt: 10}}).pretty()

Note the use of an object to contain the query operator(s).

Query Arrays

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.

Assignment

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment