Created
November 10, 2009 15:09
-
-
Save jnunemaker/230944 to your computer and use it in GitHub Desktop.
db eval to search in array of hashes with mongo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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