Skip to content

Instantly share code, notes, and snippets.

@jnunemaker
Created November 10, 2009 15:09
Show Gist options
  • Save jnunemaker/230944 to your computer and use it in GitHub Desktop.
Save jnunemaker/230944 to your computer and use it in GitHub Desktop.
db eval to search in array of hashes with mongo
require 'pp'
require 'rubygems'
require 'mongo_mapper'
require 'benchmark'
MongoMapper.database = 'testing'
class Foo
include MongoMapper::Document
key :members, Array
end
Foo.collection.remove
Foo.create(:members => [{'John' => 1, 'Steve' => 4}])
Foo.create(:members => [{'Bill' => 4, 'Frank' => 2}])
Foo.create(:members => [{'John' => 3, 'Steve' => 1}])
puts Benchmark.measure {
pp Foo.database.eval("
function(value) {
var results = [],
docs = db.foos.find({}).forEach(function(doc) {
if (doc.members) {
doc.members.forEach(function(member) {
for(key in member) {
if (key === value || member[key] === value) {
results.push(doc);
}
}
});
}
});
return results;
}
", 1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment