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?
The collectionExists method can be used to check whether a collection is present or not: MongoClient mongoClient = new MongoClient("localhost", 27017); DB db = mongoClient. getDB("baeldung"); String testCollectionName = "student"; System.
Find() Method. In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents. Cursor means a pointer that points to a document, when we use find() method it returns a pointer on the selected documents and returns one by one.
To list all collections in Mongo shell, you can use the function getCollectionNames().
If a collection does not exist, MongoDB creates the collection when you first store data for that collection. You can also explicitly create a collection with various options, such as setting the maximum size or the documentation validation rules.
Not sure how to do it through Mongoid, but in general you can query the system.namespaces collection for {name : "dbname.analyticsCachedResult"}
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With