Find file History
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Type Name Latest commit message Commit time
Failed to load latest commit information.

LESSON: mongodb



By the end of this, developers should be able to:

  • Interact with MongoDB databases and collections using the MongoDB shell.
  • Create, Read, Update, and Delete documents in MongoDB collections using the MongoDB shell.


database: all your data are belong here

collection: like a table in a relationship db, made up of columns and rows. In NoSql, a collection is a group of documents. Each document has fields and mirrors a JSON object.

BSON: short for Bin­ary JSON, is a bin­ary-en­coded seri­al­iz­a­tion of JSON-like doc­u­ments. Like JSON, BSON sup­ports the em­bed­ding of doc­u­ments and ar­rays with­in oth­er doc­u­ments and ar­rays. BSON also con­tains ex­ten­sions that al­low rep­res­ent­a­tion of data types that are not part of the JSON spec. For ex­ample, BSON has a Date type and a BinData type.

Common Mongo Commands

What's it do? command
Enter mongo repl mongo
Check what databse you're connected to db
Show all documents in a collection db.collection.find()
Show all collections show collections
Run script from command line mongo < scripts/find/people.js
list databases show dbs
use /switch to a specific database use <db_name>
find in mongodb by id db.examples.find({ _id: ObjectId('some_obj_id') })
find all in mongodb db.examples.find()
  • note about lesson

Updating Data

  • How to update a specific subset of fields using $set:
    title: 'Slaughterhouse-Five'
    $set: {
      'published_on': '1969-03-31',
      'book_cover': 'brown',
      'pages': 247

Without $set, it looks like update replaces the document with only the fields you have mentioned.

The following replaces all fields:

Finding Data

  • How to find based on if field exists, and / or if it has a Not Null value:

This will return all documents with a key called "IMAGE URL", but they may still have a null value:

db.mycollection.find({"IMAGE URL":{$exists:true}});

This will return all documents with both a key called "IMAGE URL" and a non-null value: db.mycollection.find({"IMAGE URL":{$ne:null}});

Also, according to the docs, $exists currently can't use an index, but $ne can.

Some more examples:

Given these inserts:

db.test.insert({"num":1, "check":"check value"});
db.test.insert({"num":2, "check":null});

This will return all three documents: db.test.find();

This will return the first and second documents only: db.test.find({"check":{$exists:true}});

This will return the first document only: db.test.find({"check":{$ne:null}});

This will return the second and third documents only: db.test.find({"check":null}) src

Additional links