dideler
4/13/2012 - 10:52 PM

MongoDB reminders

MongoDB reminders

Based on try.mongodb.org.

Rank  Players  Score  W D L
----  -------  -----  - - -
  1    Jim      90    2 1 0
  2    Kim      87.5  1 1 1
  3    Bob      50    0 0 3

where Score is the win/draw/loss ratio.

MongoDB is a document database. Data is stored as documents, which are similar to JS objects.

e.g.

var player = {
    name: 'Jim',
    rank: 1,
    win_draw_loss: [2, 1, 0],
    score: 90
};

To save a new player document:

db.players.save({name: 'Kim', rank: 2, win_draw_loss: [1, 1, 1], score: 87.5});

To fetch all players:

db.players.find();

To fetch specific players:

db.players.find({rank: 1}); // player with rank 1
db.players.find({rank: {'$gt': 1}}); // players with a rank greater than 1

Some other query operators are (not an exhaustive list):

'$lt', '$lte', '$gte', '$in', '$nin'

For example:

db.players.find({rank: {'$in': [1,3]}}); // players with a rank of 1 or 3

To replace an entire document:

db.players.update({name: 'Jim'}, {win_draw_loss: [3,1,0]}); // replaces every field

To (partially) update a document:

db.users.update({name: 'Cash'}, {'$set': {'age': 50} }); // set a value
db.users.update({name: 'Sue'}, {'$pull': {'languages': 'scala'} }); // pull an existing item
db.users.update({name: 'Sue'}, {'$push': {'languages': 'ruby'} });  // push a new item

To delete everything from a collection:

db.players.remove();

To delete matching documents:

db.players.remove({name: 'Kim'});

For more, check out the docs!