Get raw mongo db query expression that mongoid gen

2019-05-15 20:59发布

问题:

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.

回答1:

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 }