0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【MongoDB】データ取得のタイミングが曖昧だったのできちんとまとめてみた

Last updated at Posted at 2025-03-12

業務でmongoDBを使用しているのですがデータが取得されるタイミングが曖昧のまま実行処理をおまじないのように書くだけだったので、部下に説明するタイミングできちんと理解しようと思った今日。

おまじないコード
# 複数データを取得するときのおまじない 【.to_a rescue []】
items = item.where(category: "food").to_a rescue []
# 1件データを取得するときのおまじない 【.first rescue nil】
items = item.where(category: "food").first rescue nil

ーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーー

ruby
items = item.where(category: "food").paginate(per_page: 2, page: 1)

.where().pagination()メソッドはクエリオブジェクト(検索条件)を組み立てるだけで
DBに対する実際のクエリは実行されていない。
なので↑の状態だとデータを取得する対象のDBと検索条件が変数itemsに格納されているだけ。

.classで型を確認するとArrayではなくWillPaginate::Collectionと出力される。

ruby
items = item.where(category: "food").paginate(per_page: 2, page: 1).to_a rescue []

実際にデータを取得するためにはクエリを実行(.to_a, .first, .each() .countなど)する必要がある。

クエリオブジェクトが格納された変数を展開するとデータが表示される理由

ruby
items = item.where(category: "food").paginate(per_page: 2, page: 1)
html
<!--- 確認用 --->
<div>#{items}</div>

式展開すると.to_sが走るのでそのタイミングでクエリが実行されてデータが表示される。
実際はitemsにデータが格納されているわけではない。

ーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーー

自分の中では前よりも理解できたし、
これで調べる前よりかは理解できる説明できるかなー…

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?