How to tell whether a collection exists in MongoDB using Mongoid?
Since Mongoid.master.collection()
returns a collection even开发者_StackOverflow中文版 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?
Not sure how to do it through Mongoid, but in general you can query the system.namespaces collection for {name : "dbname.analyticsCachedResult"}
.
Using the mongo ruby driver, I extended the DB class:
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
For the gem mongoid (8.0.2)
, I use this code
client = Mongoid.default_client
current_db = client.database
current_db.collection_names.include?("name of the collection you want to check")
精彩评论