collectionsmongodbmongoid

How to tell whether a collection exists in MongoDB using Mongoid?


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?


Solution

  • Not sure how to do it through Mongoid, but in general you can query the system.namespaces collection for {name : "dbname.analyticsCachedResult"}.