Nasser Torabzade Nasser Torabzade - 1 month ago 6
Node.js Question

How to check if a collection exists in Mongodb native nodejs driver?

I need to check if a collection exists on a certain database and create it if it doesn't. I know that

db.createCollection(collName, {strict:true}, function(error, collection))


checks for existance of collection
collName
before creating it and sets
error
object. but I need an independent function to check that.

Answer

In MongoDB 3.0 and later, you have to run a command to list all collections in a database:

use test;
db.runCommand( { listCollections: 1 } );

Although querying system.namespaces will still work when you use the default storage engine (MMAPv1), it is not guaranteed to work for other engines, such as WiredTiger.

Before MongoDB 3.0 you need to do the following:

You can query the system.namespaces collection:

use test;
db.system.namespace.find( { name: 'test.' + collName } );

Like in:

db.system.namespaces.find( { name: 'test.testCollection' } );

Which returns:

{ "name" : "test.testCollection", "options" : { "flags" : 1 } }

Or of course, nothing.

See also: https://github.com/mongodb/specifications/blob/master/source/enumerate-collections.rst