2012-09-14 17 views
2

我基本上有一個User對象和內部的它是一個數組fieldphone_numbers定義。我想在我的數據庫中有一個phone_numbers用戶對象的計數超過1更大。

是否有了解類似下面的查詢的資源?我找不到任何有用的在線,因爲大部分結果都是爲更簡單的查詢。你如何找到一個場陣列中的所有記錄數超過一定量的Mongoid更大?

代碼:

class Location 
    include Mongoid::Document 

    field :name 
    field :phone_numbers, type: Array 
end 

我嘗試以下,但它沒有工作:

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

謝謝!

回答

0

試試這個:

Location.where(:phone_numbers.gte => '1').count 
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 
+0

做到了有助於在至少電話號碼? – abhas

1

這是否存在於phone_numbers[0]領域的任何物體

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

此查詢解決你的問題得到電話號碼大於1的數查詢檢索;如果存在字段phone_numbers[0]這意味着在陣列

相關問題