Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 649
nonopolarity Avatar asked Sep 23 '10 21:09

nonopolarity


People also ask

How do you check if a collection already exists in MongoDB?

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.

How do I find a particular collection in MongoDB?

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.

How do I show all collections in MongoDB shell?

To list all collections in Mongo shell, you can use the function getCollectionNames().

Does MongoDB Create collection if not exists?

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.


1 Answers

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

like image 91
kristina Avatar answered Oct 28 '22 00:10

kristina