mongodb本机驱动程序获取没有数据库名称的集合名称

Posted

技术标签:

【中文标题】mongodb本机驱动程序获取没有数据库名称的集合名称【英文标题】:mongodb native driver get collection names without database name 【发布时间】:2014-07-05 16:24:53 【问题描述】:

如何从 nodeJS 的 mongodb 本机驱动程序中获取没有数据库名称的集合名称?

db.collectionNames(function(err, collections) 
      if (err) 
        log.error(err);
       else 
        log.info(collections);
      
    );

此代码返回如下内容:

databaseName.collection1、databaseName.collection2、databaseName.collection3

但我想得到名字:collection1, collection2, collection3

【问题讨论】:

【参考方案1】:

使用 MongoDB 2.0.0 驱动程序及更高版本,您将need to use listCollections(),如

db.listCollections().toArray(function(err, collections)
    //collections = ["name": "coll1", "name": "coll2"]
);

【讨论】:

【参考方案2】:

响应的确切结构是一个带有数组中“name”键的子文档:

[
   name: 'test.cursors' ,
   name: 'test.episodes' ,
   name: 'test.zips' ,
   name: 'test.scripts' 
]

所以只需使用map 和正则表达式replace

db.collectionNames(function(err, collections) 

  console.log(
    collections.map(function(x) 
      return x.name.replace(/^([^.]*)./,"");
    )
  );

);

这将删除所有内容,直到第一个 . 是数据库前缀。以防万一您的集合名称中包含 .

【讨论】:

谢谢!太好了!

以上是关于mongodb本机驱动程序获取没有数据库名称的集合名称的主要内容,如果未能解决你的问题,请参考以下文章