Executing Mongodb Scripts Via Mongoid Rails
Solution 1:
I know this old question but in case you still need answer or any one else. This answer works with gem mongo ~> 2.3
.
The key to answer you do not need mongoid in this case - in my case I use it for rails model, so I use mongoid (5.1.0) only to get DB connection db = Mongoid.default_client.database
- or you can get/create database using mongo gem.
To execute javascript on database you need to call command
method db.command({ eval: 'js' })
or db.command({ eval: 'function(n){return db.projects.find({name: n}).toArray();}', args: ['beskhai'], nolock: true })
To get the result you can call .documents
db.command(...).documents
, The return is a hash {retval: it will be return of you script, ok: is 1 if success} the return object of command
call is [Mongo::Operation::Result]
https://github.com/mongodb/mongo-ruby-driver/blob/master/lib/mongo/operation/result.rb.
Solution 2:
I'm using MongoID 6.0.1, and it easy to query everything you want like that:
db ||= Mongoid.default_client.database
f = """
functionFoo = function (arg){
//----process arg
}
"""
result = db.command({:$eval => f, args: [arg1, arg2, ...arg_n], nolock: true})
@result_data = result.first['retval']
It not only a function, just every thing you want to do with command. My example is:
db ||= Mongoid.default_client.database
f = """
var collectionNames = db.getCollectionNames(), stats = [];
collectionNames.forEach(function (n) { stats.push(db[n].stats()); });
stats = stats.sort(function(a, b) { return b['size'] - a['size']; });
return stats;
"""
result = db.command({:$eval => f, args: [], nolock: true})
@result_data = result.first['retval']
Post a Comment for "Executing Mongodb Scripts Via Mongoid Rails"