Skip to content

Instantly share code, notes, and snippets.

@dideler
Created April 13, 2012 22:52
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 dideler/2380658 to your computer and use it in GitHub Desktop.
Save dideler/2380658 to your computer and use it in GitHub Desktop.
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!

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