如何检查一个集合是否存在于Mongodb本地nodejs驱动程序中?

我需要检查某个数据库上是否存在一个集合,如果不存在,就创build它。 我知道

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

在创build它之前检查收集collName存在并设置error对象。 但我需要一个独立的function来检查。

在MongoDB 3.0和更高版本中,您必须运行一个命令来列出数据库中的所有集合:

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

尽pipe查询system.namespaces在使用默认存储引擎(MMAPv1)时仍然可以正常工作,但不能保证可用于其他引擎,例如WiredTiger。

在MongoDB 3.0之前,您需要执行以下操作:

你可以查询system.namespaces集合:

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

像:

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

哪个返回:

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

或者当然没有。

另见: https : //github.com/mongodb/specifications/blob/master/source/enumerate-collections.rst

本机驱动程序的Db对象的collectionNames方法接受一个可选的集合名称filter作为第一个参数,以便检查集合的存在:

 db.collectionNames(collName, function(err, names) { console.log('Exists: ', names.length > 0); }); 

在MongoDB原生驱动程序的2.x版本中, collectionNameslistCollections取代,它接受一个filter并返回一个游标,所以你可以这样做:

 db.listCollections({name: collName}) .next(function(err, collinfo) { if (collinfo) { // The collection exists } }); 

从MongoDB 3.0开始,你可以简单地运行:

 db.getCollectionNames() 

它返回一个数组,其中包含当前数据库中所有集合的名称:

 [ "employees", "products", "mylogs"] 

检查Mongo数据库文档 ,或者你也可以使用db.getCollectionInfos()如果你需要更多的信息关于每个集合

Node.js本地驱动程序中现在有一个listCollections方法。 它返回当前数据库中所有集合的信息。 你可以用它来检查给定的集合是否存在:

 collectionExists = function(name, cb) { mongoDb.listCollections().toArray(function(err, collections) { if (err) return cb(err); cb(null, collections.some(function(coll) { return coll.name == name; })); }); } 

使用mongo本地驱动程序和Node.js 7.6+,我使用以下内容:

 const collections = await db.collections(); if (!collections.map(c => csname).includes(collName)) { await db.createCollection(collName); } 

这个问题涉及本地驱动程序,但我到这里search如何在pymongo做到这pymongo 。 通常pymongo的api与JS api完全相同,但在这种情况下, collection_names没有集合名称的参数(如JohnnyHK的答案 ),而是第一个参数是一个布尔值(是否包含系统集合)。 由于string评估为True ,这可能会造成混淆。 所以我希望这有助于未来的读者:

 import pymongo cl = pymongo.MongoClient() db = cl['my-db'] if 'my-col' in db.collection_names(False): ...