2

私は基本的にUserオブジェクトを持っており、その中に定義されているのは配列field phone_numbersです。phone_numbersカウントが より大きいデータベース内のすべてのユーザー オブジェクトを取得したいと考えています1

このようなクエリについて学ぶためのリソースはありますか? ほとんどの結果はより単純なクエリに対するものであったため、オンラインで役立つものは何も見つかりませんでした。

コード:

class Location
  include Mongoid::Document

  field :name
  field :phone_numbers, type: Array
end

次のことを試しましたが、うまくいきませんでした:

Location.where("this.phone_numbers.count < 1").count

ありがとう!

4

3 に答える 3

1

クエリでこの情報を確認することはできません...phone_numbers配列の数を保持するフィールドをドキュメントに作成し、このように毎回ドキュメントを保存する値を更新します

class Location
   include Mongoid::Document

   field :name
   field :phone_numbers, type: Array
   field :phone_number_count, type: Integer

   after_save do |location|
      if location.phone_numbers.blank?
         location.phone_number_count = 0
      else
         location.phone_number_count = location.phone_numbers.size 
      end
      location.save
   end
end

その後、クエリを実行できます

Location.where(:phone_number_count.gt => 1).enteries
于 2012-09-19T09:55:51.630 に答える
1

phone_numbers[0]このクエリは、フィールドにオブジェクトが存在するかどうかを検索します

Location.where(:"phone_numbers.0".exists => true).count

このクエリは、1 より大きい電話番号の数を取得する問題を解決します。フィールドが存在する場合phone_numbers[0]、配列内の少なくとも電話番号を意味します

于 2016-06-02T13:41:49.613 に答える
0

これを試して:

Location.where(:phone_numbers.gte => '1').count
于 2012-09-14T23:17:54.333 に答える