Get raw mongo db query expression that mongoid generate it

核能气质少年 提交于 2019-12-22 10:16:05

问题


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 }


来源:https://stackoverflow.com/questions/27883178/get-raw-mongo-db-query-expression-that-mongoid-generate-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!