由于
Mongoid.master.collection()
会返回一个集合,即使该集合不存在,我们也可以使用
coll = Mongoid.master.collection('analyticsCachedResult')
if coll.count == 0
# [...]
end
测试它是否是一个空集合。另一种方法是循环
Mongoid.master.collections.each do |c|
return c if c.name == 'analyticsCachedResult'
end
return nil
但是有没有更简单的方法来检测它是否存在?
不确定如何通过 Mongoid 执行此操作,但通常您可以查询 system.namespaces 集合中的
{name : "dbname.analyticsCachedResult"}
。
使用 mongo ruby 驱动程序,我扩展了 DB 类:
class Mongo::DB
def collection_exists?(collection_name)
x = "#{self.name}.#{collection_name}" # e.g., "redbike_db.clients"
nil != self['system.namespaces'].find_one({'name' => x})
end
end
对于宝石
mongoid (8.0.2)
,我使用这个代码
client = Mongoid.default_client
current_db = client.database
current_db.collection_names.include?("name of the collection you want to check")
Mongoid::Findable#exists?
exists?
将评估 true
如果集合中至少有一个文档...假设这是您的模型:
class AnalyticsCachedResult
include Mongoid::Document
store_in collection: "analyticsCachedResult"
class Foo
include Mongoid::Document
embedded_in :analytic_cached_result, inverse_of: :foos, class_name: "AnalyticsCachedResult"
end
embeds_many :foos, class_name: "AnalyticsCachedResult::Foo"
end
Foo
嵌入在分析文档中虽然两个模型都可以引用一个集合,但这并不意味着它们都会生成一个集合:
AnalyticsCachedResult.collection.name
# => "analyticsCachedResult"
AnalyticsCachedResult::Foo.collection.name
# => "analytics_cached_result_foos"
所以当还没有文档时,
exists?
它会返回false
AnalyticsCachedResult.exists?
# => false
AnalyticsCachedResult::Foo.exists?
# => false
现在让我们创建一个文档并保存它:
acr = AnalyticsCachedResult.new
acr.foos.build({})
acr.save!
您的顶级模型现在将评估
true
:
AnalyticsCachedResult.exists?
# => true
虽然有一个
AnalyticsCachedResult::Foo
文档,但它存储为 嵌入到 AnalyticsCachedResult
中,因此它的集合将为空:
acr.fooes.first
# => #<AnalyticsCachedResult::Foo _id: 111122223333444455556666, >
AnalyticsCachedResult::Foo.exists?
# => false