如何在 Mongoid 中查找字段数组计数大于一定数量的所有记录?

问题描述 投票:0回答:4

我基本上有一个

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

谢谢!

ruby-on-rails mongoid
4个回答
2
投票

此查询搜索

phone_numbers[0]
字段中是否存在任何对象

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

此查询解决了获取大于 1 的电话号码计数的问题;如果存在该字段

phone_numbers[0]
,则表示数组中至少有电话号码


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
投票

我在搜索避免聚合的解决方案失败后才得到这个想法:

array_sizes_to_avoid = (0..1).map do |avoid_count| 
  { phone_numbers: { '$size' => avoid_count } }
end
User.not(User.any_of(array_sizes_to_avoid))

虽然有点笨重,但很管用。


-1
投票

试试这个:

Location.where(:phone_numbers.gte => '1').count
© www.soinside.com 2019 - 2024. All rights reserved.