如何使用 Mongoid 判断 MongoDB 中是否存在集合?
由于即使集合不存在,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
,但是有没有更简单的方法来检测是否存在呢?
Since Mongoid.master.collection()
returns a collection even if the collection doesn't exist, we can use
coll = Mongoid.master.collection('analyticsCachedResult')
if coll.count == 0
# [...]
end
to test if it is an empty collection. Another method is to loop through
Mongoid.master.collections.each do |c|
return c if c.name == 'analyticsCachedResult'
end
return nil
but is there a simpler way to detect whether it exists?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不确定如何通过 Mongoid 执行此操作,但通常您可以在 system.namespaces 集合中查询
{name : "dbname.analyticsCachedResult"}
。Not sure how to do it through Mongoid, but in general you can query the system.namespaces collection for
{name : "dbname.analyticsCachedResult"}
.使用 mongo ruby 驱动程序,我扩展了 DB 类:
Using the mongo ruby driver, I extended the DB class:
对于 gem
mongoid (8.0.2)
,我使用此代码For the gem
mongoid (8.0.2)
, I use this code您可能正在寻找
Mongoid::Findable#exists ?
exists?
将评估true
如果集合中至少有一个文档...让我们假设这是您的模型:
虽然两个模型都可以引用集合,但这并不意味着它们将各自生成一个集合:
因此,当还没有文档时,
存在吗?
它将返回false
现在让我们创建一个文档并保存它:
您的顶级模型现在将评估
true
:尽管有一个
AnalyticsCachedResult::Foo
文档,它嵌入AnalyticsCachedResult
中存储,因此其集合将为空:You are probably looking for
Mongoid::Findable#exists?
exists?
will evaluatetrue
if at least there is one document in the collection...Let's assume this is your model:
Foo
is embedded in the analytics documentWhile both models can refer to a collection, that does not mean they will generate a collection each:
So when there are no documents yet,
exists?
it will returnfalse
Now let's create one document and persist it:
Your top model will now evaluate
true
:And although there is one
AnalyticsCachedResult::Foo
document, it is stored embedded inAnalyticsCachedResult
, and therefore its collection will be empty: