Executing mongodb scripts via mongoid Rails

I have a mongo db script in a js file:

query.js

//conn = new Mongo(); //db = conn.getDB("dbName"); functionFoo = function (arg){ //----process arg } 

I also have an args array known as args_array (which I retrieve from the database using mongoid), for which I want to do something like this:

 args_array.each do |arg| //some how call functionFoo(arg) from the query.js file end 

is this possible on rails?

I can execute the file from the terminal, but I want to wrap it in my application so that I can use it from the rails console.

+1
source share
2 answers

I know this old question, but in case you still need an answer or whatever. This answer works with gem mongo ~> 2.3 .

The key to the answer is you don’t need mongoid in this case - in my case I use it for the rails model, so I use mongoid (5.1.0) only to get the DB connection db = Mongoid.default_client.database - or you can get / create databases data using mango jewels.

To execute javascript in the database, you need to call the 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 . Return is a hash {retval: this will return you script, ok: is 1 if success} return object of the command call [Mongo::Operation::Result] https://github.com/mongodb/mongo-ruby-driver/blob /master/lib/mongo/operation/result.rb .

This article can help you.

+2
source

I am using MongoID 6.0.1, and it is easy to request everything you want:

  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'] 

This is not only a function, just every thing you want to do with a team. My example:

 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'] 
0
source

Source: https://habr.com/ru/post/1393093/


All Articles