Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get raw mongo db query expression that mongoid generate it

I want to get the mongoid generated mongo query expression how to do it ?

e.g. this is the mongoid syntax

History.where(report_type: params["report_type"]).order_by(ts:1).only(:ts).last

I want to have the method, such as to_sql, to get the native query expression so that I can apply it on Mongo console.

like image 960
user3675188 Avatar asked Sep 01 '25 10:09

user3675188


1 Answers

MongoDB doesn't really have a query language like SQL so you can't get the whole thing in one nice compact piece. You can, however, get the pieces.

This:

History.where(report_type: params["report_type"]).order_by(ts:1).only(:ts)

builds a Mongoid::Criteria. That's more or less the Mongoid version of the underlying query. You can extract the query by calling selector:

q = History.where(report_type: params["report_type"]).order_by(ts:1).only(:ts)
q.selector
# { 'report_type' => whatever_was_in_params }

the ordering by looking at options[:sort]:

q.options[:sort]
# { 'ts' => 1 }

and the fields are in options[:fields]:

q.options[:fields]
# { 'ts' => 1 }
like image 169
mu is too short Avatar answered Sep 04 '25 17:09

mu is too short