LoginSignup
4
5

More than 5 years have passed since last update.

MongoDBでCollectionの最新分ドキュメントをサクッと取得したいとき

Last updated at Posted at 2015-05-13

インサートされた順にドキュメントが(だいたい)並んでいます。
このnatural orderの逆から、30件取得するには次のように書きます。

col.class # => Mongo::Collection
res = col.find( {}, sort: { "$natural"=> -1 }, limit: 30 ).to_a

自分はドキュメントに日付を書いておくことが多いので、
「あれ、このコレクションてちゃんと更新して使ってるやつだっけ?」
と思った時などに叩いています(汗)

Collectionの最終更新日付を取得する

逆natural orderからドキュメントをいくらか取り出して、値に含まれるTimeオブジェクトを集めて、それらのうち一番新しいものを最終更新時間と考えます。

class Hash
  def hash_values
    vals = []
    values.each{|v| Hash === v ? vals.concat(v.hash_values) : vals << v }
    vals
  end
end

class Mongo::Collection
  def estimate_latest_update_time(docsize=10)
    res = find( {}, sort: { "$natural"=> -1 }, limit: docsize, fields: { _id: 0 } ).to_a
    res.map(&:hash_values).flatten.select{|v| Time === v }.sort.last
  end
end
col.estimate_latest_update_time
# => 2015-04-11 12:11:27 UTC

参考

mongoDBでだいたい新しい順番にドキュメントを取得する - NullPointer's Blog
http://paulownia.hatenablog.com/entry/2012/11/24/182952

4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5