MongoDB - SeanHolden/Wiki GitHub Wiki

###1. JavaScript Shell

The first thing to notice is that the MongoDB shell is JavaScript-based.

So you can do things like:

  a = 5; 

  a * 10; 

  for(i=0; i<10; i++) { print('hello'); }; 

###2. Documents

MongoDB is a document database. This means that we store data as documents, which are similar to JavaScript objects. Here below are a few sample JS objects:

  var a = {age: 25}; 

  var n = {name: 'Ed', languages: ['c', 'ruby', 'js']}; 

  var student = {name: 'Jim', scores: [75, 99, 87.2]};

###3. Saving

Here's how you save a document to MongoDB:

db.scores.save({a: 99});

This says, "save the document '{a: 99}' to the 'scores' collection."

Go ahead and try it. Then, to see if the document was saved, try

db.scores.find();

###4. Saving and Querying

Try adding some documents to the scores collection:

for(i=0; i<10; i++) { db.scores.save({a: i, exam: 5}) }; 

Try that, then enter

db.scores.find();

to see if the save succeeded. Since the shell only displays 10 results at time, you'll need to enter the 'it' command to iterate over the rest.

###5. Basic Queries

You've already tried a few queries, but let's make them more specific.

How about finding all documents where a == 2:

db.scores.find({a: 2}); 

Or what about documents where a > 15?

db.scores.find({a: {'$gt': 15}});

###6. Query Operators

Query Operators:

$gt is one of many special query operators. Here are few others:

  $lt  - '<',   $lte - '<=', 

  $gte - '>=',  $ne  - '!='

  $in - 'is in array',  $nin - '! in array'
db.scores.find({a: {'$in': [2, 3, 4]}}); 

db.scores.find({a: {'$gte': 2, '$lte': 4}}); 

###7. Updates

Now create a couple documents like these for updating:

db.users.save({name: 'Johnny', languages: ['ruby', 'c']}); 
db.users.save({name: 'Sue', languages: ['scala', 'lisp']}); 

Make sure they were saved by calling db.users.find()

Update the first document like so:

db.users.update({name: 'Johnny'}, {name: 'Cash', languages: ['english']}); 

###8. Update Operators

The previous update replaced the entire document, but MongoDB also

supports partial updates to documents. For example, you can set a value:

db.users.update({name: 'Cash'}, {'$set': {'age': 50} });

You can also push and pull items from arrays:

db.users.update({name: 'Sue'}, {'$pull': {'languages': 'scala'} });
db.users.update({name: 'Sue'}, {'$push': {'languages': 'ruby'} }); 

###9. Deleting data

To delete matching documents only, add a query selector to the remove method:

db.users.remove({name: 'Sue'});

To delete everything from a collection:

db.scores.remove();