我需要检查一个集合是否存在于某个数据库上,如果没有,就创建它。我知道如何检查一个集合是否存在于Mongodb本地nodejs驱动程序中?
db.createCollection(collName, {strict:true}, function(error, collection))
检查收集collName
的所有脑干创建它之前,并设置error
对象。但我需要一个独立的功能来检查。
我需要检查一个集合是否存在于某个数据库上,如果没有,就创建它。我知道如何检查一个集合是否存在于Mongodb本地nodejs驱动程序中?
db.createCollection(collName, {strict:true}, function(error, collection))
检查收集collName
的所有脑干创建它之前,并设置error
对象。但我需要一个独立的功能来检查。
在MongoDB中3.0和更高版本,你必须运行一个命令列出所有集合在一个数据库:
use test;
db.runCommand({ listCollections: 1 });
虽然查询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
方法接受一个可选的集合名称过滤器作为第一个参数来让你检查一个集合的存在:
db.collectionNames(collName, function(err, names) {
console.log('Exists: ', names.length > 0);
});
在MongoDB本地驱动程序的2.x版本中,collectionNames
已被替换为listCollections
,它接受一个过滤器并返回一个光标,因此您可以这样做:
db.listCollections({name: collName})
.next(function(err, collinfo) {
if (collinfo) {
// The collection exists
}
});
这应该是被接受的答案,因为它是实际处理node.js的唯一答案(如OP所要求的)。 – DanFromGermany
也是一个班轮'db.listCollections({name:colName})。hasNext()' – cyberwombat
@JohnyHK,如果集合存在,如何获取该集合的记录 –
问题涉及本机驱动程序,但我在这里搜索如何在pymongo
中执行此操作。通常pymongo
的api与JS api相同,但在这种情况下,collection_names
没有该集合名称的参数(如JohnnyHK
的answer的第一个参数是布尔值) )。由于字符串评估为True
,这可能会造成混淆。所以我希望这可以帮助未来的读者:
import pymongo
cl = pymongo.MongoClient()
db = cl['my-db']
if 'my-col' in db.collection_names(False):
...
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;
}));
});
}
由于MongoDB 3。0您可以简单地运行:
db.getCollectionNames()
它会返回所有集合的当前数据库名称的数组:
[ "employees", "products", "mylogs"]
检查Mongo DB Documentation,或者你也可以使用db.getCollectionInfos(),如果你需要了解每个集合
getCollectionNames()方法在node.js中不可用本地库。 – DanFromGermany
嘿,但我使用它从mongodb库,这是一个管理mongo数据库@DanFromGermany – Roberto
['Db.collectionNames()'](https://mongodb.github.io/node-mongodb -native/markdown-docs/collections.html#list-existing-collections),但根本不包含getCollectionNames()。 – DanFromGermany
使用mongo-native司机和Node.js 7.6+更多的信息,我使用以下命令:
const collections = await db.collections();
if (!collections.map(c => c.s.name).includes(collName)) {
await db.createCollection(collName);
}
需要更多信息:您正在使用哪个连接器库,并检查了它的manual/api文档? –
@ Mike'Pomax'Kamermans我正在使用[mongo-native](https://github.com/mongodb/node-mongodb-native)驱动程序库,并且我无法在API文档中找到这些功能。 (mongo-native](https://github.com/mongodb/node-mongodb-native)中的 –