Skip to content

Instantly share code, notes, and snippets.

@olivoil
Created February 16, 2011 04:15
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 olivoil/828855 to your computer and use it in GitHub Desktop.
Save olivoil/828855 to your computer and use it in GitHub Desktop.
MongoDB code examples for Montreal.rb presentation // in Javascript
// Create database - Just use it, it gets created on the fly if it doesn't exist yet
use blog_development;
// Create table - Collections are schema-less, no need to declare a structure.
// They are also created on the fly when you use them
show collections;
// Create index
// Indexing on _id is done automatically by mongoDB
// with the only exception of Capped Collections (more on this later...)
db.articles.ensureIndex( { author_id:1 } );
// Articles may or may not have a title field. Queries will only retrieve documents with a title
db.articles.ensureIndex( { title : 1 }, { sparse : true } );
// users without a first or last name will have these fields set to null
// a duplicate key error will be raised if trying to insert two users with the same first AND last names
db.users.ensureIndex( { first_name: 1, last_name: -1}, {unique: true} );
// Indexed fields may be of any type, including documents.
db.articles.ensureIndex( { 'comments.author_id': 1 }); OR db.articles.ensureIndex({ comments: 1 });
// db.articles.getIndexes(); to check indexes on a collection
// db.system.indexes.find(); to check all existing indexes on the db
// db.articles.find( { title: 'Yet another blog post' } ).explain(); to check what indexes are used
// Insert data
var article = { author_id: ObjectID('4d547108ae7b1cf342000008'),
created_at : new Date('02/15/2011'),
title : 'Yet another blog post',
text : 'Here is the text...',
tags : [ 'example', 'joe' ],
comments : [
{ author_id: ObjectID('4d547108ae7b1cf342000010'), comment: 'I disagree' },
{ author_id: ObjectID('4d547108ae7b1cf342000011'), comment: 'Good post' }
]
};
// save() works too, although if the document already exists (same _id), it will update it
db.articles.insert( article ); OR db.articles.save( article );
// Query data
// find all articles
db.articles.find();
// find articles based on the title
db.articles.find( { title: 'Yet another blog post' } );
// find articles based on the author, only fectch the title back
db.articles.find( { author_id: ObjectID('4d547108ae7b1cf342000008') }, { title: 1 });
// find articles commented by their author
db.articles.find(
{ author_id: ObjectID('4d547108ae7b1cf342000008'),
'comments.author_id': ObjectID('4d547108ae7b1cf342000008')
}, {
title: 1, 'comments.content': 1
});
// find recent articles with either
// a title containing 'rails',
// comments containing 'rails',
// or tagged with 'rails' or 'ruby'
db.articles.find( {
created_at: { $gte: new Date('01/01/2011') },
$or: [
{ title: /rails|ruby/i },
{ 'comments.content' : /rails|ruby/im },
{ tags: { $in: [ 'rails', 'ruby' ] } }
]
}, {
title: 1, created_at: 1, author_id: 1
}).sort( { created_at: -1, title: 1 } ).skip( 100 ).limit( 10 );
// Will not work !
// Embedded documents cannot (yet) be accessed without going through their parent
db.comments.find( { author_id: ObjectID('4d547108ae7b1cf342000008') });
// JS EVAL
db.articles.find(
'this.title.match( /ruby/i ) &&
this.created_at >= new Date("01/01/2011")'
)
db.articles.find({
published: true,
$where: "this.title.match( /montreal/i )"
});
// JS Functions
db.articles.find({
$where: function(){
return this.tags.length > 3;
}
});
// Geolocation
// Let's say we have a field with latitude / longitude :
{ location : [ 50 , 30 ] }
{ location : { x : 50 , y : 30 } }
{ location : { foo : 50 , y : 30 } }
{ location : { lat : 40.739037, long: 73.992964 } }
// Create an index on the field
db.articles.ensureIndex( { location : "2d" } )
// Same as db.articles.ensureIndex( { location : "2d" } , { min : -180 , max : 180 } )
// Query data based on location
db.articles.find( { location : [50,50] } )
db.articles.find( { location : { $near : [50,50] , $maxDistance : 5 } } ).limit(20)
// Compound indexes
db.articles.ensureIndex( { location : "2d" , tags : 1 } );
db.articles.find( { location : { $near : [50,50] }, tags : 'ruby' } );
// If your world isn't flat
db.articles.find( { location: { $nearSphere : [ 50, 50 ], num: 10)
db.runCommand( { geoNear : "articles" , near : [ 50 , 50 ], num : 10, spherical: true)
// Capped collections
db.createCollection("log", {capped:true, size:100000}) // max size in bytes
db.createCollection("log", {capped:true, size:100000, max: 100}) // max number of objects
// Counting unique tags with Map Reduce
var map = function() {
if (!this.tags) {
return;
}
for (index in this.tags) {
emit(this.tags[index], 1);
}
};
var reduce = function(previous, current) {
var count = 0;
for (index in current) {
count += current[index]
}
return count;
};
db.articles.mapReduce(map, reduce, { out: 'articles_tags_aggregation' });
// Update data
db.articles.update( { title: /another blog post/},
{ $set: { title: 'Not just another blog post'},
$addToSet: { tags: { $each: ['atomic', 'awesome' ] } },
true, // upsert - same as just using save()
false // update only the first matched document
});
// db.collection.update( criteria, objNew, upsert, multi )
// criteria [ Hash ] the query used to find matching documents
// objNew [ Hash ] updated object or $ operators (e.g., $set) which manipulate the object
// upsert [ Boolean ] if true => update if present, insert if missing - default to false with update()
// multi [ Boolean ] if all documents matching criteria should be updated, false by default
// $ operators include:
// $inc, $set, $unset, $push, $pushAll, $addToSet, $pop, $pull, $pullAll, $rename, $bit
db.articles.update(
{ _id:ObjectID('4e829472cd7f1cf342000012') ,
'comments.author_id': ObjectID('4d547108ae7b1cf342000010')
}, {
$set: { 'comments.$.content': 'I completely agree' }
});
// db.runCommand( "getlasterror" ).updatedExisting === true
// will tell you if your request caused an existing object to be updated
// more on this later...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment