MongoDB MongoID 动态查询方法

kevinhua · 2012年04月05日 · 最后由 sqsy 回复于 2014年01月16日 · 3425 次阅读

看了 MongoID 的官方文档,貌似没有类似 find_by_fieldname 的动态查询方法,需要动态查询,有两种实现方法:

@node = Node.where(slug: params[:slug]).find(:first)

@node = Node.first(conditions: { slug, params[:slug] })

这两种方法,性能貌似等价,使用

10000.times do |i|
  puts Time.now if i==1
  方法一:@node = Node.where(slug: "movie").find(:first)
  方法二:@node = Node.first(conditions: {slug: "movie"})
  puts Time.now if i==9999
end

运行 10000 次数据库查询 (包括逻辑判断),都需要约 14 秒。

@node = Node.where(slug: "movie")[0]

10000 次查询能节省 2 秒时间。

用 Benchmark bmbm 更好。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号