MongoDB MongoID 动态查询方法

kevinhua · April 05, 2012 · Last by sqsy replied at January 16, 2014 · 3425 hits

看了 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 更好。

You need to Sign in before reply, if you don't have an account, please Sign up first.