[SERVER-1938] create db.exists() and collections.exists() Created: 13/Oct/10  Updated: 06/Apr/23

Status: Backlog
Project: Core Server
Component/s: Shell
Affects Version/s: None
Fix Version/s: None

Type: New Feature Priority: Minor - P4
Reporter: Brennan Pang Assignee: Massimiliano Marcon
Resolution: Unresolved Votes: 29
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Depends
Participants:

 Description   

Add a db.exists() and collections.exists() so that it is easy to check whether a database or a collection exists. This will help to reduce the propensity to inadvertently create new dbs and collections when running a script due to typos.



 Comments   
Comment by Steven Vannelli [ 10/May/22 ]

Moving this ticket to the Backlog and removing the "Backlog" fixVersion as per our latest policy for using fixVersions.

Comment by Massimiliano Marcon [ 11/Feb/21 ]

Tracking this request in our feedback portal to be considered for the new MongoDB Shell: https://feedback.mongodb.com/forums/929233-mongodb-shell/suggestions/42686618-add-support-for-db-exists-and-collections-exists

Comment by Wernfried Domscheit [ 11/Feb/21 ]

Would this workaround be sufficient? 

( db.adminCommand( { listDatabases: 1, nameOnly: true, filter: { name: "database_name" } } ).databases.length ) > 0
(db.getCollectionNames().indexOf("collection_name") > -1)

 

Comment by Frédéric G. MARAND [ 20/Apr/20 ]

In the specific case I need this for, the need arises when checking the schema for one specific collection which needs to be capped. But if I just "create" the collection then run "convertToCapped", the convertion command fails with an error reporting the database does not exist. I don't won't to touch the collection if it already exists, which I can't know if it is empty.

The problem is that "createCollection" does not actually create the collection, so does not create the database. But then the convertToCapped fails because of that.

Workaround: before running the conversion command, I insert a dummy row in the collection, which this time actually creates the database to hold the collection, then the collection. After which I can remove the document, then run the conversion works, and finally get the fresh new empty capped collection.

 

Comment by Asya Kamsky [ 20/Apr/20 ]

fgm@osinet.fr I assume you mean it no longer works...

In fact, it does work but it's changed.

If the database does not exist, then stats shows

	"collections" : 0,
	"views" : 0,
	"objects" : 0,
	"avgObjSize" : 0,
	"dataSize" : 0,
	"storageSize" : 0,
	"numExtents" : 0,
	"indexes" : 0,
	"indexSize" : 0,

Once anything is created in the DB, you would see:

	"collections" : 1,
etc.

To be honest I don't really understand what it means for the database to exist - if it has nothing in it.
Or for a collection for that matter.

Maybe someone can explain why they need this functionality with some examples.

Comment by Frédéric G. MARAND [ 18/Apr/20 ]

The solution suggested by @asya does work with current versions (4.2). With a non existent database, we no longer get an error:

> db.getSiblingDB('logger').xxx.stats()
{ 
  "ns" : "logger.xxx", 
  "size" : 0, 
  "count" : 0, 
  "storageSize" : 0, 
  "nindexes" : 0, 
  "totalIndexSize" : 0, 
  "indexSizes" : { 
 
  }, 
  "scaleFactor" : 1, 
  "ok" : 1
}
> db.xxxxxxx.stats()
{ 
  "ns" : "logger.xxxxxxx", 
  "size" : 0, 
  "count" : 0, 
  "storageSize" : 0, 
  "nindexes" : 0, 
  "totalIndexSize" : 0, 
  "indexSizes" : {
 
  }, 
  "scaleFactor" : 1, 
  "ok" : 1
}

 

Comment by Jonas Barr [ 22/Jan/20 ]

Adding another idea,
collection.insertOne / insertMany could return a flag on whether the collection exists or did this operation created the collection in the process.
We need to perform multiple operations whenever a new collection is created, and checking for listCollection on every insert is bad...
We're currently  caching the collection list like Ivan does but still

so +1 as well. thanks...

Comment by Ivan Filimonov [ 30/Nov/18 ]

I get I'm supposed to call listCollections with a query to do this, but it places DB lock for some reason. I have a database with a 1000s of collections and i need to check if new ones were added quite often, from different processes. Also I can't have them accidentally created because of indexing stuff, so I need to run listCollections basically on every connection attempt. As a result I'm having queues building up.

I've worked around that by caching the results of listCollections calls in memory for specific collections, but it would break as soon as I decided to drop some of those collection for any reason (in fact i actually want to do this).

I could also do collStat, and there's nothing in docs that suggests locks (though there still might be some that were not documented), but there's a different problem with it. When it fails because the collection doesn't exist - it fails fast, which is fine. But when the collection exists it gets predictably slow, cause it does need some time to gather all the data it returns.

So yeah, +1 please.

Comment by Asya Kamsky [ 16/Aug/18 ]

db.getSiblingDB("foobar").xxx.stats()
{
   "ns" : "foobar.xxx",
   "ok" : 0,
   "errmsg" : "Database [foobar] not found."
}
db.xxxxxxxxxxx.stats()
{
   "ns" : "test.xxxxxxxxxxx",
   "ok" : 0,
   "errmsg" : "Collection [test.xxxxxxxxxxx] not found."
} 

Comment by Christian Tonhäuser [ 25/Feb/16 ]

+1 for increasing the priority of this feature.
We need to do a lot of stupid things in our code in order to make sure a DB exists without accidently creating it.
Would be perfect if we could do without that...

An even better alternative would be that getDB() and getCollection() calls get an optional flag to prevent automatic creation of DBs/collections and rather let the call fail.

Comment by John Kunze [ 03/Jan/16 ]

Yes, please increase priority of this issue.

Comment by Nazar Volynets [ 12/Feb/14 ]

Moreover in case of Mongo Security "readWrite" role - there is no way of checking db existence that doesn't lead to its creation.
Please increase priority of this issue.

Comment by Sergey Smirnov [ 01/Apr/13 ]

This can be a great feature. While it still doesn't exists, programmers have to use db.collection.find().limit(1) to check if the document exists. See this article:
http://blog.serverdensity.com/checking-if-a-document-exists-mongodb-slow-findone-vs-find/

Comment by Nikhil Prabhakar [ 26/Apr/11 ]

MapReduce operation throws error if collection doesn't exist. Need a quick way to check whether coll exists or not before starting MapReduce operation.

Comment by Joachim De Lombaert [ 07/Dec/10 ]

We would also find it useful to have a shortcut to check whether a collection exists. Currently (using the PHP driver) we're checking whether the collection is present in system.namespaces, similar to how the MongoCollection class in the PHP driver implements listCollections.

Generated at Thu Feb 08 02:58:30 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.